tags:

views:

177

answers:

2

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?

+4  A: 

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;
}
kitchen
+4  A: 

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.

doron
Done like this, there's still a gap between the delete and the rename. On UNIX filesystems, you should fsync, skip the delete, and just rename the temporary file over the first file; it will be atomically replaced. On Windows, NTFS has a special ReplaceFile function; atomic replacements are not doable on other filesystems AFAIK.
ephemient