C/C++ Insight: Input & Output

@ 2009-07-16 23:31:23
标签:

    输入输出(I/O)是程序设计中的不可缺少的部分。狭义的I/O是通常是指文件或者标准输入输出的读写,广义的I/O则要范围广大的多。

    预定义输入输出 object

    • cin 标准输入
    • cout 标准输出。缓冲输出(Buffered Output)
    • cerr 标准错误输出。非缓冲输出(Unbuffered Output)
    • clog 默认和 cerr 一样绑定在 stdio 的标准错误输出上。

    重定向 clog 到文件

    TODO

    读取文件内容

    #include <iostream>
    #include <ifstream>
    
    std::ifstream fin("file.txt");
    
    // 按字节读取
    while( !fin.eof() ){
        char c = fin.get();
        std::cout<<c;
        // 可以“偷看”下一个字符
        if (fin.peek() == 'd') {
            // 下一个字符是 d
         }
    }
    
    // 或者按块读取
    char buf[1024];
    fin.seekg (0, ios::beg);
    while(!fin.eof()){
        fin.read(buf,1024);
        int nBytes = fin.gcount();
        std::cout<< nBytes <<" bytes read"<<std::endl;
    }
    
    // 或者按行读取
    char line[1024];
    fin.seekg (0, ios::beg);
    while(!fin.eof()){
        fin.getline(line,1024); // 读取最多1024-1 = 1023 个字符或者遇到 '\n'(被丢弃)为止
        // 也可以自己指定“行”分隔符
        // 比如 fin.getline(line,1024,'\0');
        std::cout<<fin.gcount()<<" bytes read"<<std::endl;
    }
    

    输入输出缓冲

    C++ 的 iostream 是已经使用了缓冲区的。因此,可以不用像在 C 中那样自己建立缓冲区。关于缓冲的一个可能问题是缓冲区究竟要多大才合适。一个常见的大小是 4096 字节(4KB大小)。如果需要自己指定缓冲区大小,可以参考 streambuf 的 pubsetbuf 方法。

    重载输出运算符 <<

    // 重载输出运算符 &lt;&lt;
    ostream &amp; operator&lt;&lt; (ostream &amp; os, const myClass &amp; rhs);
    
    // 为了能够访问 myClass 的私有成员,声明为 friend 成员如下
    class myClass {
    
       friend ostream &amp; operator&lt;&lt; (ostream &amp; lhs, const myClass &amp; rhs);
     
       private:
         int myData;
    }
    
    标签:

      分享到:
      comments powered by Disqus

      19/21ms