1.文件操作 程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放。通过文件可以将数据持久化。
C++ 中对文件操作需要包含头文件 <fstream> 文件类型分为两种:
-
文本文件 - 文件以文本的 ASCII 码形式存储在计算机中
-
二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们
操作文件的三大类:
-
ofstream:写操作
-
ifstream:读操作
-
fstream:读写操作
1.2 文本文件 5.1.1 写文件 写文件步骤如下:
-
包含头文件#include <fstream>
-
创建流对象ofstream ofs;
-
打开文件ofs.open("文件路径", 打开方式);
-
写数据ofs << "写入的数据";
-
关闭文件ofs.close();
| 打开方式 | 解释 |
|---|---|
ios::in |
为读文件而打开文件 |
ios::out |
为写文件而打开文件 |
ios::ate |
初始位置:文件尾 |
ios::app |
追加方式写文件 |
ios::trunc |
如果文件存在先删除,再创建 |
ios::binary |
二进制方式 |
cpp
#include <iostream>
#include <fstream>
using namespace std;
// 写文件
void writeFile() {
ofstream ofs("test.txt",ios::out); // 创建并打开文件
ofs << "Hello, File Operation!" << endl;
ofs << "C++文件操作测试" << endl;
ofs.close(); // 关闭文件
}
// 读文件
void readFile() {
ifstream ifs("test.txt",ios::in);
if (!ifs.is_open()) { // 判断文件是否成功打开
cout << "文件打开失败" << endl;
return;
}
string buf;
while (getline(ifs, buf)) { // 按行读取
cout << buf << endl;
}
ifs.close();
}
int main() {
writeFile();
readFile();
return 0;
}
2.1二进制文件 以二进制的方式对文件进行读写操作。
打开方式要指定为 ios::binary。
2.2写文件 二进制方式写文件主要利用流对象调用成员函数 write。
函数原型:ostream& write(const char * buffer, int len);
参数解释:字符指针 buffer 指向内存中一段存储空间,len 是读写的字节数。
cpp
#include <iostream>
#include <fstream>
using namespace std;
class Person {
public:
char m_Name[64]; // 姓名
int m_Age; // 年龄
};
int main() {
// 1. 包含头文件
// 2. 创建流对象
ofstream ofs;
// 3. 打开文件,指定为二进制写模式
ofs.open("person.bin", ios::out | ios::binary);
Person p = {"张三", 18};
// 4. 写数据(将Person对象以二进制形式写入)
ofs.write((const char*)&p, sizeof(Person));
// 5. 关闭文件
ofs.close();
cout << "二进制文件写入完成" << endl;
return 0;
}