如何在C ++中同时使用`fstream`在文件中读写? [英] How to read and write in file with `fstream` simultaneously in c++?

查看:304
本文介绍了如何在C ++中同时使用`fstream`在文件中读写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main(void) {
    fstream ofile;
    ofile.open("test.txt", ios::in | ios::out | ios::app);
    for(string line; getline(ofile, line) ; ) {
        cout << line << endl;
    }
    ofile << "stackexchnange" << endl;
    ofile.close();
    return 0;
}

test.txt包含

hello world!
stackoverflow

以上代码输出

hello world!
stackoverflow

并且在运行代码后,stackexchange不会附加在test.txt的末尾.如何读取然后写入文件?

And after running the code stackexchange is not appending at the end of test.txt. How to read and then write in file?

推荐答案

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;

这篇关于如何在C ++中同时使用`fstream`在文件中读写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆