I'm trying to read data from a text file, clear it, and then write to it, in that order using the fstream
class.
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?
Clear a Text File Using the open() Function in write Mode Opening a file in write mode clears its data. Also, if the file specified doesn't exist, Python will create a new one. The simplest way to delete a file is to use open() and assign it to a new variable in write mode.
The + adds either reading or writing to an existing open mode, aka update mode. The r means reading file; r+ means reading and writing the file. The w means writing file; w+ means reading and writing the file. The a means writing file, append mode; a+ means reading and writing file, append mode.
'r+' opens the file for both reading and writing. On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
You should open it, perform your input operations, and then close it and reopen it with the std::fstream::trunc flag set.
#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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With