- 头文件:
#include<fstream>
using namespace std;
- 创建文件流:
fstream fstr;
ifstream ifstr;
ofstream ofstr;
- 打开文件:
fstr.open("xxx.xxx", mode, access); //用fstream打开文件,要设置打开文件的模式
ifstr.open("xxx.xxx"); // ifstream默认以输入(读)方式打开文件
ofstr.open("xxx.xxx"); //ofstream默认以输出(写)方式打开文件
- 文件模式:
| |
---|
in | 以读方式打开 |
out | 以写方式打开 |
app | 每次写操作之前均定位到文件末尾 |
ate | 打开文件后立即定位到文件末尾 |
trunc | 截断文件 |
binary | 以二进制方式进行IO |
- 文件属性:
| |
---|
0 | 普通文件,打开访问 |
1 | 只读文件 |
2 | 隐含文件 |
4 | 系统文件 |
- 读文件:
char str[10];
ifstr.read(str, sizeof(str)); //把文件中字符串写到str中,长度为sizeof(str)
ifstr >> str; //把文件中字符串写到str中
- 写文件:
char str[] = "write to file.";
ofstr.write(str, sizeof(str)); //把字符串写到文件中,长度为sizeof(str)
ofstr << str; //吧字符串写到文件中
注意:在linux中,如果要写操作文件,需要先更改文件的操作权限。