zoukankan      html  css  js  c++  java
  • C++Primer,C++标准IO库阅读心得

    IO 标准库类型和头文件


    iostream istream 从流中读取
        ostream 写到流中去
        iostream 对流进行读写;从 istream 和 ostream 派生而来
    fstream ifstream 从文件中读取;由 istream 派生而来
        ofstream 写到文件中去;由 ostream 派生而来
        fstream 读写文件;由 iostream 派生而来
    sstream istringstream 从 string 对象中读取;由 istream 派生而来
        ostringstream 写到 string 对象中去;由 ostream 派生而来
        stringstream 对 string 对象进行读写;由 iostream 派生而来

    1 一个文件流对象再次使用时要先clear

    ifstream& open_file(ifstream &in, const string &file)
    {
    in.close(); // close in case it was already open
    in.clear(); // clear any existing errors
    // if the open fails, the stream will be in an invalid state
    in.open(file.c_str()); // open the file we were given
    return in; // condition state is good if open succeeded
    }

    2 打开文件时要检查对象状态

    ifstream input;
    vector<string>::const_iterator it = files.begin();
    // for each file in the vector
    while (it != files.end()) {
    input.open(it->c_str()); // open the file
    // if the file is ok, read and "process" the input
    if (!input)
    break; // error: bail out!
    while(input >> s) // do the work on this file
    process(s);
    input.close(); // close file when we're done with it
    input.clear(); // reset state to ok
    ++it; // increment iterator to get next file
    }

    3 文件打开模式组合

    out 打开文件做写操作,删除文件中已有的数据
    out | app 打开文件做写操作,在文件尾写入
    out | trunc 与 out 模式相同
    in 打开文件做读操作
    in | out 打开文件做读、写操作,并定位于文件开头处
    in | out | trunc 打开文件做读、写操作,删除文件中已有的数据

  • 相关阅读:
    PAT甲级——1095 Cars on Campus (排序、映射、字符串操作、题意理解)
    PAT甲级——1096 Consecutive Factors (数学题)
    PAT甲级——1097 Deduplication on a Linked List (链表)
    博客作业06--图
    博客作业05--查找
    博客作业04--树
    博客作业03--栈和队列
    博客作业2---线性表
    博客作业01-抽象数据类型
    C语言最后一次作业--总结报告
  • 原文地址:https://www.cnblogs.com/mingzhang/p/9905783.html
Copyright © 2011-2022 走看看