Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from file, clear it, write to it

Tags:

c++

file

file-io

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?

like image 488
Anonymous Avatar asked Jan 16 '10 08:01

Anonymous


People also ask

How do you clear a text file and write it in Python?

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.

What is A+ mode in Python?

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.

How do I open a text file in write and read 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'.


2 Answers

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;
}
like image 119
xian Avatar answered Sep 20 '22 13:09

xian


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.

like image 37
doron Avatar answered Sep 20 '22 13:09

doron