c++怎么把对象数组写入文件
时间: 2024-05-07 19:23:12 浏览: 14
在 C++ 中,可以使用文件流 (fstream) 来将对象数组写入文件。具体步骤如下:
1. 定义一个类,该类包含需要写入文件的数据成员和一个默认构造函数。
2. 创建一个对象数组。
3. 打开一个文件流,将文件以二进制格式打开。例如:
```c++
ofstream outFile("data.txt", ios::out | ios::binary);
```
4. 将对象数组写入文件。可以使用 write() 函数来完成此操作。例如:
```c++
outFile.write(reinterpret_cast<char*>(objectArray), sizeof(objectArray));
```
此处的 `reinterpret_cast<char*>` 将对象数组的地址转换为 char* 类型,以便 write() 函数可以将其写入文件。
5. 关闭文件流。例如:
```c++
outFile.close();
```
完整代码示例:
```c++
#include <iostream>
#include <fstream>
using namespace std;
class Person {
public:
string name;
int age;
Person() {
name = "";
age = 0;
}
};
int main() {
Person people[3];
people[0].name = "Alice";
people[0].age = 20;
people[1].name = "Bob";
people[1].age = 25;
people[2].name = "Charlie";
people[2].age = 30;
ofstream outFile("data.txt", ios::out | ios::binary);
outFile.write(reinterpret_cast<char*>(people), sizeof(people));
outFile.close();
return 0;
}
```
这样就可以将对象数组写入文件了。