从偏移量读取写入
bool CReadWrite::write(unsigned long long offset, void* pvsrc, unsigned long long nbytes)
{ int WriteResult;
pFile = fopen("D:\\myfile.bin","wb");
if (!pFile){
puts("Can't open file");
return false;
}
//offset = fseek(pFile,offset,
WriteResult = fwrite (pvsrc, 1, nbytes, pFile);
if (WriteResult == nbytes){
puts("Wrote to file");
fclose(pFile);
return true;
}
else{
puts("Unable to write to File.");
fclose(pFile);
return false;
}
}
到目前为止,这是我的班级功能。我基本上是在打开一个文件,检查它是否确实打开(如果没有打开)。写入文件,检查文件是否确实被写入返回 true。否则返回 false。正如你可以从我的参数看出的,我正在寻找创建一个偏移量,我可以在其中给出特定的偏移量,即 10,并从 10 开始,然后从那里写入。我确信我需要使用 fseek,但我不能假设我位于文件的开头或文件中的任何位置。我很确定我需要使用 SEEK_SET 但我可能是错的。对于实现上述愿望有什么想法吗?谢谢。
bool CReadWrite::write(unsigned long long offset, void* pvsrc, unsigned long long nbytes)
{ int WriteResult;
pFile = fopen("D:\\myfile.bin","wb");
if (!pFile){
puts("Can't open file");
return false;
}
//offset = fseek(pFile,offset,
WriteResult = fwrite (pvsrc, 1, nbytes, pFile);
if (WriteResult == nbytes){
puts("Wrote to file");
fclose(pFile);
return true;
}
else{
puts("Unable to write to File.");
fclose(pFile);
return false;
}
}
This is my class function so far. I'm basically opening a file, checking to see if it did indeed open if not get out. Writes the file, checks to see if the file see if the file was indeed written to returns true. else return false. As you can tell by my parameters, I'm looking to create an offset where I can give a particular offset i.e. 10, and start from 10 and then from there write. I know for sure I need to use fseek but I can't assume that I'm at the beginning of the file or anywhere in the file. Im pretty sure i need to use SEEK_SET but I may be wrong. Any thoughts on implemented the above desires? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用的
fopen
没有附加设置(就像您一样,“wb”创建一个空文件),您可以假设您正处于开头。无论如何,
SEEK_SET
将位置设置为距开头的给定偏移量。如果文件没有您想要的偏移量(就像您的情况一样),那么问题是您需要做什么?如果只是填充 - 然后写入
offset
填充字节,然后写入您的内容,否则也许您想使用“a”而不是“w”。 “w”截断文件的现有内容,而“a”打开追加并将位置设置到现有内容的末尾。更多详细信息请参见此处。
If you're using
fopen
without the append setting (as you are, "wb" creates an empty file), you can assume you're at the beginning.Regardless,
SEEK_SET
sets the position to the given offset from the beginning.If the file doesn't have the offset that you want to seek to (as it is in your case), then the question is what are you required to do? If just pad - then write
offset
padding bytes, and then your content, otherwise maybe you wanted to use "a" and not "w". "w" truncates the existing content of the file, while "a" opens for append and sets position to the end of the existing content.More details here.