【发布时间】:2019-06-17 08:04:14
【问题描述】:
我正在尝试使用下面提供的函数 owrite 在给定偏移量处以“wb”模式写入一个新文件,但每次它都会覆盖偏移量之前的所有字节。 使用 windows 10、visual studio 2019 16.0.3。
偏移量是正数并且超出文件范围(因为它是一个新文件)。 count == 64000 == buf 的大小。
我尝试使用 lseek/_lseek write/_write(使用 fileno),但结果相似。 owrite 不返回 -1,还检查了 fwrite 的输出,一切似乎都很好。执行此操作的正确方法是什么?
int owrite(FILE* fd, char* buf, size_t count, int offset)
{
if (fseek(fd, offset, SEEK_SET) != 0) {
return -1;
}
fwrite((char*)buf, sizeof(char), count, fd);
fseek(fd, 0, SEEK_SET);
return 0;
}
这里还有调用 owrite 的函数:
void insert_chunk(byte* buffer, int len, char* filename, long offset)
{
FILE* builded_file = fopen(filename, "wb");
owrite(builded_file, buffer, len, offset);
fclose(builded_file);
}
//byte is unsigned char
【问题讨论】:
-
如果它是一个新文件,它的开始和你寻找的偏移量之间没有任何字节。如果有,请发布显示问题的Minimal Reproducible Example。
-
如果您需要写入现有文件的偏移量,请使用
"r+b"模式。
标签: c windows visual-studio binaryfiles