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 打开文件做读、写操作,删除文件中已有的数据

猜你喜欢

转载自www.cnblogs.com/mingzhang/p/9905783.html