I am trying to pwrite
some data at some offset of a file with a given file descriptor. My data is stored in two vectors. One contains unsigned long
s and the other char
s.
I thought of building a void *
that points to the bit sequence representing my unsigned long
s and char
s, and pass it to pwrite
along with the accumulated size. But how can I cast an unsigned long
to a void*
? (I guess I can figure out for chars then). Here is what I'm trying to do:
void writeBlock(int fd, int blockSize, unsigned long offset){
void* buf = malloc(blockSize);
// here I should be trying to build buf out of vul and vc
// where vul and vc are my unsigned long and char vectors, respectively.
pwrite(fd, buf, blockSize, offset);
free(buf);
}
Also, if you think my above idea is not good, I'll be happy to read suggestions.
You cannot meaningfully cast an unsigned long
to a void *
. The former is a numeric value; the latter is the address of unspecified data. Most systems implement pointers as integers with a special type (that includes any system you're likely to encounter in day-to-day work) but the actual conversion between the types is considered harmful.
If what you want to do is write the value of an unsigned int
to your file descriptor, you should take the address of the value by using the &
operator:
unsigned int *addressOfMyIntegerValue = &myIntegerValue;
pwrite(fd, addressOfMyIntegerValue, sizeof(unsigned int), ...);
You can loop through your vector or array and write them one by one with that. Alternatively, it may be faster to write them en masse using std::vector
's contiguous memory feature:
std::vector<unsigned int> myVector = ...;
unsigned int *allMyIntegers = &myVector[0];
pwrite(fd, allMyIntegers, sizeof(unsigned int) * myVector.size(), ...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With