I'm tryi开发者_如何转开发ng 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?
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.
精彩评论