C++ 从文件中读取,清除它,写入它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2076723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:01:48  来源:igfitidea点击:

Read from file, clear it, write to it

c++filefile-io

提问by Anonymous

I'm trying to read data from a text file, clear it, and then write to it, in that order using the fstreamclass.

我正在尝试从文本文件中读取数据,清除它,然后使用fstream类按顺序写入它。

My question is how to clear a file after reading from it. I know that I can open a file and clear it at the same time, but is there some function I can call on the stream to clear its contents?

我的问题是如何在读取文件后清除文件。我知道我可以打开一个文件并同时清除它,但是我可以在流上调用一些函数来清除它的内容吗?

回答by xian

You should open it, perform your input operations, and then close it and reopen it with the std::fstream::trunc flag set.

您应该打开它,执行您的输入操作,然后关闭它并使用 std::fstream::trunc 标志集重新打开它。

#include <fstream>

int main()
{
    std::fstream f;
    f.open("file", std::fstream::in);

    // read data

    f.close();
    f.open("file", std::fstream::out | std::fstream::trunc);

    // write data

    f.close();

    return 0;
}

回答by doron

If you want to be totally safe in the event of a crash or other disastrous event, you should do the write to a second, temporary file. Once finished, delete the first file and rename the temporary file to the first file. See the Boost Filesystemlibrary for help in doing this.

如果您想在发生崩溃或其他灾难性事件时完全安全,您应该写入第二个临时文件。完成后,删除第一个文件并将临时文件重命名为第一个文件。有关执行此操作的帮助,请参阅Boost 文件系统库。