Talk is cheap, show me the code.
流不能复制。
ofstream o1, o2;
o1 = o2; //wrong流不能直接作为函数形参或者返回值,但可以使用流的引用或者指针:
ofstream & fun1(ofstream &); //right
ofstream * fun2(ofstream *); //right
ofstream fun3(ofstream); //wrong流有四种状态,bad,fail,eof和good,只有good状态才是有效状态,这四个状态分别由badbit,failbit,eofbit和goodbit控制,可以通过setstate来控制。
ifstream ifs1;
ifs1.setstate(badbit | failbit); //同时将badbit和failbit置为1输出流缓存区的刷新,可以通过显示输出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;如果程序需要利用一个流对象读取多个文件,那么每次处理完一个文件必须关闭流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++;
}文件打开模式,默认是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模式打开文件输入流和打开文件输出流分别有两种方式,一种是直接定义流时调用构造函数,另一种是先定义流后调用open函数打开对应文件。
ifstream input1("test.txt"); //输入流方式一
ifstream input2;
input2.open("test.txt"); //输入流方式二
ofstream output1("test1.txt"); //输出流方式一
ofstream output2;
output2.open("test1.txt"); //输出流方式二包含头文件sstream,即可使用stringstream, istringstream, ostringstream流对象,但个人觉得这个字符串流没有多大优势,也可以很轻易被其他方式取代。