4

我正在研究一些使用 win32WriteFile()写入二进制文件中的随机位置的遗留代码。写入的偏移量可以超过文件的末尾,在这种情况下,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
    }
}

那么我唯一的选择是“手动”0从当前 EOF 写入 s 到 soffset吗?

4

1 回答 1

2

这是我从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 是否也失败。如果是这样,您可以更早地检测到故障。

于 2012-03-09T19:41:03.220 回答