1.1头文件
需要包含头文件#include “fstream”
1.2读写文件概括
写入文件:创建ofstream对象,使用ofstream方法,如 << 和 write()
读取文件:创建ifstrean对象,使用ifstream方法,如 >> 和 get()
2.1写入文件
创建ofstream对象,使用调用open()打开文件,使用 << 方式写入文件
也可以调用构造函数,不调用open()方法
int main(){
ofstream fout;
fout.open("新建文本文档.txt");
ofstream fout("新建文本文档.txt");
fout << "hello world";
fout.close();//显示关闭输出流
return 0;
}
这里的写入文件原则是:该文件存在,新内容将覆盖旧内容
该文件不存在,直接创建该文件(同程序源代码处于一个文件下)
ostream是ofstream的基类,因此可以使用ostream里的所有方法包括:插入运算符定义、格式化方法、控制符
ofstream使用缓冲输出的方法,举个例子,创建两个ofstream对象,程序便会创建两个缓冲区
缓冲的优点:提高程序写入速度
2.2读取文件
读取文件同写入文件相似
int main(){
ifstream fin;
//ifstream fin("新建文本文档.txt");
fin.open("新建文本文档.txt");
char ch;
while(fin.get(ch)){
cout << ch;
}
fin.close();//显示关闭输入流
return 0;
}
close()方法不会删除流,只是断开流的链接(流仍会被保留)
2.3读写文件应用
int main(){
string filename;
cin >> filename;//输入文件名
//ofstream fout(filename.c_str());
ofstream fout;
fout.open(filename.c_str());//创建文本文件,c_str()提供c风格字符串
fout << "0001, zhangsan, 19, 100\n";
fout << "0002, wangwu, 18, 99";
fout.close();
//ifstream fin(filename.c_str());
ifstream fin;
fin.open(filename.c_str());
char ch;
while(fin.get(ch)){
cout << ch;
}
fin.close();
return 0;
}
也可以使用构造函数省略open()操作
3.1流状态检查
进行文件操作前先使用is_open()进行检查
if(fin.is_open()){
}
3.2打开多个文件
int main(){
ifstream fin;
fin.open("test.txt");
char ch;
while(fin.get(ch)){
cout << ch;
}
cout << endl;
fin.close();
fin.clear();
fin.open("test2.txt");
while(fin.get(ch)){
cout << ch;
}
fin.close();
return 0;
}
使用同一个流处理文件,减少占用计算机资源,提高效率
3.3文件模式
fstream finout;
finout.open("test.txt", ios::in | ios::out | ios::binary);
常量 | 含义 |
---|---|
ios_base::in | 打开文件,以便读入 |
ios_base::out | 打开文件,以便写入 |
ios_base::ate | 打开文件,并移到文件尾 |
ios_base::app | 追加到文件尾 |
ios_base::trunc | 如果文件存在,则截断文件 |
ios_base::binary | 二进制文件 |
4.1其他概念
流:进出程序的字节流
缓冲区:内存的临时存储区
seekg():将输入指针移到指定位置
seekp():将输出指针移到指定位置
tellg()、tellp():报告文件当前位置