C++ 用c ++清除文本文件中的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17032970/
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
clear data inside text file in c++
提问by Zeyad
I am programming on C++. In my code I create a text file, write data to the file and reading from the file using stream, after I finish the sequence I desire I wish to clear all the data inside the txt file. Can someone tell me the command to clear the data in the txt file. Thank you
我在 C++ 上编程。在我的代码中,我创建了一个文本文件,将数据写入文件并使用流从文件中读取,在完成我希望的序列后,我希望清除 txt 文件中的所有数据。谁能告诉我清除txt文件中数据的命令。谢谢
回答by PureW
If you simply open the file for writing with the truncate-option, you'll delete the content.
如果您只是使用 truncate 选项打开文件进行写入,您将删除内容。
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
回答by Thomas Matthews
Deleting the file will also remove the content. See remove file.
删除文件也将删除内容。请参阅删除文件。
回答by 1911 Soldier
If you set the trunc flag.
如果你设置了 trunc 标志。
#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
}
I tested this thouroughly for my own needs in a common programming situation I had. Definitely be sure to preform the ".close();" operation. If you don't do this there is no telling whether or not you you trunc or just app to the begging of the file. Depending on the file type you might just append over the file which depending on your needs may not fullfill its purpose. Be sure to call ".close();" explicity on the fstream you are trying to replace.
我在我遇到的常见编程情况下根据自己的需要对此进行了彻底测试。一定要确保执行“.close();” 手术。如果您不这样做,则无法确定您是否截断或只是应用程序来请求文件。根据文件类型,您可能只是附加在文件上,这取决于您的需要可能无法实现其目的。一定要调用“.close();” 明确地在您要替换的 fstream 上。
回答by Issaic Belden
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
据我所知,只需在没有追加模式的情况下以写入模式打开文件就会删除文件的内容。
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
第一个将位置位放在开始擦除所有内容,而第二个版本将位置位放在文件结束位并从那里写入。