基于流的文件IO
头文件
ofstream : 写文件
ifstream : 读文件
fstream : 读写文件
using namespace std;
//打开文件
std::ifstream fin("xxx.txt");
//std::ifstream fin;
//fin.open("xxx.txt");
std::ofstream fout("xxxx.txt");
if (!fin.is_open()) //判断文件是否打开成功
{
cout << "打开文件异常" << endl;
fin.clear();
}
//从文件读取一个字符
char ch;
fin >> ch; //read a character from the file
char buf[80];
fin >> buf; //read a word from the file
fin.getline(buf, 80); //read a line from the file
string line;
getline(fin, line); //read from a file to a string object
fout<< line;
fout.close();
fin.close();
fin.clear(); //reset fin
- 文件模式
将流与文件关联时(无论所雇佣文件名初始化文件流对象,还是使用open()方法),都可以指定文件模式第二个参数:
ifstream fin(“xxxxx.txt”,openMode1);
ofstream fout();
fout.open(“xxxxx.txt”,openMode2);
常量 | 含义 |
---|---|
ios_base::in | 打开文件,以便读取 |
ios_base::out | 打开文件,以便写入 |
ios_base::ate | 打开文件,并移到文件尾 |
ios_base::app | 追加到文件尾 |
ios_base::trunc | 如果文件存在,截断文件(清空旧文件) |
ios_base::binary | 二进制文件 |
ifstream open()方法和构造函数用ios_base::in(打开文件以读取)作为模式参数的默认值,而ofstream open()方法和构造函数用 ios_base::out|ios_base::trunc(打开文件,以写入并截断文件)作为默认参数。位运算符or(|)用于将两个位值合并成为一个可用于设置两个位的值。
- c++mode与cmode对应关系
c++模式 | c模式 | 含义 |
---|---|---|
ios_base::in | “r” | 打开以读取 |
ios_base::out|ios_base::trunc | “w” | 打开以写入,如果已存在,则覆盖 |
ios_base::out|ios_base::app | “a” | 打开以写入,只追加 |
ios_base::out|ios_base::out | “r+” | 打开以读写,在文件允许的位置写入 |
ios_base::out|ios_base::out|ios_base::trunc | “w+” | 打开以读写,如果已存在,首先覆盖 |
c++mode|ios_base::binary | “cmode”+“b” | 以c++mode(或相应cmode)和二进制模式打开;例如:ios_base::in|ios_base::binary成为"rb" |
c++mode|ios_base::ate | “cmode” | 以指定模式打开,并移到文件尾。C是使用一个独立的函数调用,而不是模式编码。例如:ios_base::in|ios_base::ate 被转换为"r"模式打开,然后调用fseek(file,0,SEEK_END) |
注意:ios_base::ate和ios_base::app都将文件指针指向打开的文件末尾。二者的区别在于,ios_base::app模式只允许将数据添加到文件末尾,而ios_base::ate模式是将指针放到文件尾。