Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear data inside text file in c++

Tags:

c++

fstream

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

like image 878
Zeyad Avatar asked Jun 10 '13 21:06

Zeyad


People also ask

How do you clear the contents of a text file in C++?

If you simply open the file for writing with the truncate-option, you'll delete the content.


Video Answer


2 Answers

If you simply open the file for writing with the truncate-option, you'll delete the content.

std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();

http://www.cplusplus.com/reference/fstream/ofstream/open/

like image 117
PureW Avatar answered Oct 22 '22 10:10

PureW


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.

like image 10
Issaic Belden Avatar answered Oct 22 '22 10:10

Issaic Belden