C++primer第4版第八章标准IO库

Talk is cheap, show me the code.

  1. 流不能复制。

    ofstream o1, o2;
    o1 = o2; //wrong

  2. 流不能直接作为函数形参或者返回值,但可以使用流的引用或者指针:

    ofstream & fun1(ofstream &); //right
    ofstream * fun2(ofstream *); //right
    ofstream fun3(ofstream); //wrong

  3. 流有四种状态,bad,fail,eof和good,只有good状态才是有效状态,这四个状态分别由badbit,failbit,eofbit和goodbit控制,可以通过setstate来控制。

    ifstream ifs1;
    ifs1.setstate(badbit | failbit); //同时将badbit和failbit置为1

  4. 输出流缓存区的刷新,可以通过显示输出flush,endl,ends或者unitbuf来刷新缓存区,其中flush不输出任何字符,直接刷新缓存区,endl输出换行符然后刷新缓存区,ends输出NULL字符然后刷新缓存区,unitbuf相当于每次写入操作后都会进行flush,可以通过nounitbuf来回复系统管理缓存区的模式。 另外,标准库将cin和cout绑定在了一起,即每次cin读入一次都会自动刷新cout的缓存区进行一次输出。

    cout << "hello" << flush;
    cout << "hello" << endl;
    cout << "hello" << ends;
    cout << unitbuf << "hello" << nounitbuf;

  5. 如果程序需要利用一个流对象读取多个文件,那么每次处理完一个文件必须关闭流close()和清除流状态clear():

    vector<string> vect = {"file1", "file2"};
    vector<string>::iterator it = vect.begin();
    ifstream input;
    string s;
    while (it != vect.end())
    {
    input.open(it->c_str());
    if (!input)
    break;
    while(input >> s)
    process(s);
    input.close();
    input.clear();
    it++;
    }

  6. 文件打开模式,默认是ofstream::out, ifstream::in, ofstream::app:

    in 打开文件做读操作
    out 打开文件做写操作,直接覆盖原有内容
    app 在每次写之前找到文件尾,在原文件内容后追加内容,而不是覆盖原有内容
    ate 打开文件后立即将文件定位在文件尾
    trunc 打开文件时清空已存在的文件流
    binary 以二进制模式进行IO操作

    ifstream input("test.txt", ifstream::in); //不加后面的in模式,默认也是in模式
    ofstream output("test1.txt", ofstream::app); //想要在文件后追加内容,必须指定模式为app,否则默认是out模式

  7. 打开文件输入流和打开文件输出流分别有两种方式,一种是直接定义流时调用构造函数,另一种是先定义流后调用open函数打开对应文件。

    ifstream input1("test.txt"); //输入流方式一
    ifstream input2;
    input2.open("test.txt"); //输入流方式二
    ofstream output1("test1.txt"); //输出流方式一
    ofstream output2;
    output2.open("test1.txt"); //输出流方式二

  8. 包含头文件sstream,即可使用stringstream, istringstream, ostringstream流对象,但个人觉得这个字符串流没有多大优势,也可以很轻易被其他方式取代。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值