我正在处理一些遗留代码,这些代码使用 win32 WriteFile()
写入二进制文件中的随机位置。写入的偏移量可以超过文件末尾,在这种情况下 WriteFile()
似乎会自动将文件大小扩展到偏移量,然后将数据写入文件。
我想使用 std::fstream
做同样的事情,但是当我尝试 seekp()
到适当的位置时,超过了文件,seekp()
失败,随后的 write()
也失败。
所以在我看来,我必须“手动”填充当前 EOF 和我要写入的位置之间的空间。
代码如下所示:
void Save(size_t offset, const Element& element)
{
m_File.seekp(offset, std::ios_base::beg);
m_File.write(reinterpret_cast<const char*>(&element), sizeof(Element));
if (m_File.fail()) {
// ... error handling
}
}
那么我唯一的选择是“手动”从当前 EOF 写入 0
到 offset
吗?
最佳答案
这是我从 MSDN 中逐字提取的示例:
// basic_ostream_seekp.cpp
// compile with: /EHsc
#include <fstream>
#include <iostream>
int main()
{
using namespace std;
ofstream x("basic_ostream_seekp.txt");
streamoff i = x.tellp();
cout << i << endl;
x << "testing";
i = x.tellp();
cout << i << endl;
x.seekp(2); // Put char in third char position in file
x << " ";
x.seekp(2, ios::end); // Put char two after end of file
x << "z";
}
文件“basic_ostream_seekp.txt”在程序末尾有te ting\0\0z
,也就是说,您可以搜索文件末尾。
无论如何,如果 write 对您来说确实失败了,您可以检查并查看 seekp 是否也失败了。如果是,您可以更早地检测到故障。
关于c++ - 在读/写 fstream 上查找/写入某个位置时自动扩展文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9603107/