- 程序运行时产生的数据都属于临时数据,程序一旦结束运行都会被释放。
- 通过文件可以将数据持久化。
- C++中对文件的操作需要包含头文件
- 文本文件:文件以文本的ASCII码形式存储在计算机中
- 二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂他们
- ofstream:写操作
- ifstream:读操作
- fstream:读写操作
- 包含头文件
#include
- 创建流对象
ofstream ofs;
- 打开文件
ofs.open("文件路径",打开方式); - 写数据
ofs<<"写入的数据";
- 关闭文件
ofs.close();
- ios::in——为读文件而打开文件
- ios::out——为写文件而打开文件
- ios::ate——初始位置在文件尾
- ios::app——追加方式写文件
- ios::trunc——如果文件存在先删除,再创建
- ios::binary——二进制方式
注意:文件打开方式可以配合使用,利用 | 操作符
ios::binary | ios::out ; //以二进制方式写文件
读文件
- 包含头文件
#include
- 创建流对象
ifstream ifs;
- 打开文件,并判断是否打开成功
ifs.open("文件路径",打开方式); if( ! ifs.is_open() ) { cout<<"文件打开失败"< - 读数据——四种方式读取文件
//第一种 char buf[1024] = {0}; while ( ifs >> buf ) { cout << buf << endl; } //第二种 char buf[1024] = {0}; while ( ifs.getline( buf, sizeof(buf) ) ) { cout << buf << endl; } //第三种 string buf; while( getline(ifs, buf) ) { cout << buf << endl; } //第四种 char c; while( (c = ifs.get()) != EOF ) { cout << c << endl; } - 关闭文件
ifs.close();
- 主要利用流对象调用成员函数read、write
- 函数原型:
ostream& write(const char * buffer, int len); istream& read(char * buffer, int len);
- 参数解释:字符指针buffer指向内存中的一段存储空间,len是读写的字节数
- 关键代码:
//写 ofs.open("person.txt", ios::out | ios::binary); ofs.write( (const char *)&p, sizeof(Person) ); //读 ifs.open("person.txt", ios::in | ios::binary); ifs.read( (char *)&p, sizeof(Person) );



