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

时间:2021-02-25 09:17:27

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

我正在尝试从文本文件中读取数据,清除它,然后使用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?

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

2 个解决方案

#1


15  

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;
}

#2


4  

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 Filesystem library for help in doing this.

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

#1


15  

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;
}

#2


4  

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 Filesystem library for help in doing this.

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