无法在读取后写入具有入和出选项的文件流

Cant write after reading to file stream with in and out options

本文关键字:选项 文件 读取      更新时间:2023-10-16

我的文件流有问题。我需要的是打开文件,读取它,然后在上面写一些值

        std::string filename;
    std::fstream save_file;
    save_file.open(SAVED_HASH, std::fstream::in | std::fstream::out | std::fstream::binary);
    while (save_file >> filename);
    save_file.seekg(save_file.beg);
    save_file << " more lorem ipsum";
    save_file.close();

当我尝试运行它时,我得到的只是一个空文件。但如果我去掉第四行,它就行了。这个代码有什么问题,为什么我不能读取文件,然后写

我能发现的一个错误是之后

while (save_file >> filename); 

您需要清除错误标志。

save_file.clear();

此外,IMO您需要使用seekp而不是seekg,因为您想在该位置"写入"。

有关示例,请参见此链接http://www.cplusplus.com/reference/ostream/ostream/seekp/?kw=seekp