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 longs and the other chars.
I thought of building a void * that points to the bit sequence representing my unsigned longs and chars, 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 longto avoid *. 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 intto your file descriptor, you should take the address of the value by using the&operator: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: