Pir*_*ooz 4 c++ file-io casting
我正在尝试pwrite
使用给定文件描述符在文件的某个偏移量处的某些数据.我的数据存储在两个向量中.一个包含unsigned long
s和另一个包含char
s.
我想构建一个void *
指向代表我的unsigned long
s和char
s 的位序列,并将其传递给pwrite
累积大小.但我怎么能投unsigned long
一个void*
?(我想我可以找出字符然后).这是我正在尝试做的事情:
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);
}
Run Code Online (Sandbox Code Playgroud)
另外,如果您认为我的上述想法不好,我会很乐意阅读建议.
你无法有意义地投入unsigned long
到void *
.前者是数值; 后者是未指定数据的地址.大多数系统将指针实现为具有特殊类型的整数(包括您在日常工作中可能遇到的任何系统),但这些类型之间的实际转换被认为是有害的.
如果你想要做的是将a的值写入unsigned int
文件描述符,你应该使用运算符获取值的地址&
:
unsigned int *addressOfMyIntegerValue = &myIntegerValue;
pwrite(fd, addressOfMyIntegerValue, sizeof(unsigned int), ...);
Run Code Online (Sandbox Code Playgroud)
你可以遍历你的矢量或数组,并用它逐个编写它们.或者,使用std::vector
连续的内存功能集中编写它们可能会更快:
std::vector<unsigned int> myVector = ...;
unsigned int *allMyIntegers = &myVector[0];
pwrite(fd, allMyIntegers, sizeof(unsigned int) * myVector.size(), ...);
Run Code Online (Sandbox Code Playgroud)