我正在使用C++进行编程。在我的代码中,我创建了一个文本文件,并使用流将数据写入文件并从文件中读取,当我完成所需的序列后,我希望清除txt文件中所有的数据。有人能告诉我清除txt文件数据的命令吗?谢谢
如果你使用截断选项打开文件进行写入,那么你将会删除原有内容。
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
第一个版本会将位置位放在开头并清除所有内容,而第二个版本会将位置位放在文件结束位上并从那里开始写入。
#include<fstream>
using namespace std;
fstream ofs;
int main(){
ofs.open("test.txt", ios::out | ios::trunc);
ofs<<"Your content here";
ofs.close(); //Using microsoft incremental linker version 14
}
我在自己的实际编程需求中进行了彻底测试。一定要执行".close();"操作。如果不这样做,就无法确定您是否截断或者只是追加到文件的开头。根据文件类型,您可能只是追加到文件上,这根据您的需求可能无法达到目的。一定要显式调用要替换的fstream上的".close();"。
void clear()
{
ofstream file("fileout.txt");
file<<"";
}