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

Ano*_*ous 14 c++ file-io file

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

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

xia*_*ian 15

您应该打开它,执行输入操作,然后关闭它并使用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;
}
Run Code Online (Sandbox Code Playgroud)