文件输入输出--c++复习(7)
一、标准IO库
1.对控制台的读写:<iostream>,包含cin、cout对象
2.对文件的读写:<fstream>
3.对字符串的读写:<sstream>
二、文件的输入输出*
1.打开文件
1.1创建文件对象时以构造函数打开文件:ofstream outfile("test.txt",ios::out);第一个参数是文件路径,第二个参数是打开模式
1.2使用open函数打开文件:
1 ofstream ofile 2 ofile.open("/tmp/test.txt",ios::out)
1.3打开模式:
app追加;ate文件指针指向文件尾;binary打开二进制文件;in以输入方式打开,只读;out以输出方式打开,只写;trunc覆盖,清除文件数据;
可以结合使用“|”运算符,指定多个模式:ios::in||ios::out ios::in||ios::binary
1.4实例
1 //写文件 2 void write() 3 { 4 ofstream out; 5 out.open("test.txt",ios::out); 6 if(!out.fail())//判断文件是否打开成功 7 { 8 out<<"tim "; 9 out<<"mail "; 10 out.flush();//刷新缓冲区 11 } 12 out.close();//关闭流 13 } 14 15 //读文件 16 void read() 17 { 18 ifstream in; 19 in.open("test.txt",ios::in); 20 char c; 21 while(!in.eof())//判断是否到达文件末尾 22 { 23 c=in.get(); 24 cout<<c; 25 } 26 cout<<endl; 27 in.close(); 28 }