Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在读/写流中查找/写入到某个位置时自动扩展文件大小_C++_Fstream_Seek_Random Access_Eof - Fatal编程技术网

C++ 在读/写流中查找/写入到某个位置时自动扩展文件大小

C++ 在读/写流中查找/写入到某个位置时自动扩展文件大小,c++,fstream,seek,random-access,eof,C++,Fstream,Seek,Random Access,Eof,我正在编写一些旧代码,它使用win32WriteFile()写入二进制文件中的随机位置。写入的偏移量可以超过文件的末尾,在这种情况下,WriteFile()似乎会自动将文件大小扩展到偏移量,然后将数据写入文件 我想使用std::fstream来做同样的事情,但是当我尝试seekp()到适当的位置,超过文件的结尾时,seekp()失败,随后的write()也失败 因此,在我看来,我必须“手动”填充当前EOF和我要写入的位置之间的空间 代码如下所示: void Save(size_t offset,

我正在编写一些旧代码,它使用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
    }
}
void保存(大小偏移、常量元素和元素)
{
seekp(偏移量,std::ios\u base::beg);
m_File.write(reinterpret_cast(&element),sizeof(element));
if(m_File.fail()){
//…错误处理
}
}

因此,我唯一的选择是从当前EOF到偏移量“手动”写入
0
s?

下面是一个我逐字从中获得的示例:

//basic\u ostream\u seekp.cpp
//使用:/EHsc编译
#包括
#包括
int main()
{
使用名称空间std;
流x(“basic_ostream_seekp.txt”);
streamoff i=x.tellp();

很抱歉,我最终放弃了基于std::fstream的代码,因为CRT最多只能分配2k个文件句柄,这对我们来说是不够的。至于你的答案,从ios::end搜索似乎确实有效。奇怪的是,从ios::beg搜索失败。我也想搜索文件的末尾。我在W上用VS 2010进行了测试indows和Linux(我们目前的两个平台)上的一些相当新的GCC版本,以及
ios::beg
ios::end
[编辑:虽然绝对准确,但我认为我使用了
seekp
的one-arg形式,而不是明确指定
ios::beg
]。可能是由于其他原因,
ios::beg
在liwp中失败了?在我的例子中,文件是用
ios::In | ios::out | ios::binary
打开的;我不确定这是否会有什么不同。我发现令人沮丧的是,关于“文件的结尾”案例的实际文档很少。
// 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";
}