且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++中同时使用`fstream`在文件中读写?

更新时间:2023-02-05 17:17:43

Nawaz的评论正确.您的读取循环将反复进行,直到fstream::operator bool(为ofile)返回false.因此,在循环之后,必须设置failbit或badbit.当循环尝试最后一次读取时,将设置failbit,但只剩下EOF可供读取.完全可以,但是在尝试再次使用流之前,您必须重置错误状态标志.

Nawaz' comment is correct. Your read loop iterates until the fstream::operator bool (of ofile) returns false. Therefore, after the loop, either failbit or badbit must have been set. failbit is set when loop tries to read for the final time but only EOF is left to read. This is completely OK, but you must reset the error state flag before trying to use the stream again.

// ...
ofile.clear();
ofile << "stackexchnange" << endl;