输入输出(I/O)是程序设计中的不可缺少的部分。狭义的I/O是通常是指文件或者标准输入输出的读写,广义的I/O则要范围广大的多。
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 方法。
// 重载输出运算符 <<
ostream & operator<< (ostream & os, const myClass & rhs);
// 为了能够访问 myClass 的私有成员,声明为 friend 成员如下
class myClass {
friend ostream & operator<< (ostream & lhs, const myClass & rhs);
private:
int myData;
}