C++ 对象数组文件存储与读取教程:详细步骤与示例代码
保存对象数组到文件:
-
打开文件,以写入模式打开,可以使用
ofstream类。 -
将对象数组写入文件,可以使用文件流中的
write()函数,将对象数组的地址作为参数,同时指定写入的字节数。 -
关闭文件,以确保写入操作完成,可以使用文件流中的
close()函数。
示例代码:
#include <iostream>
#include <fstream>
using namespace std;
class Person {
public:
string name;
int age;
};
int main() {
Person people[3] = {{"Tom", 20}, {"Jack", 25}, {"Lucy", 30}};
ofstream outFile("people.dat", ios::out | ios::binary);
if (!outFile.is_open()) {
cout << "Open file failed." << endl;
return -1;
}
outFile.write((char*)people, sizeof(people));
outFile.close();
return 0;
}
从文件读取对象数组:
-
打开文件,以读取模式打开,可以使用
ifstream类。 -
将文件中的数据读取到对象数组中,可以使用文件流中的
read()函数,将对象数组的地址作为参数,同时指定读取的字节数。 -
关闭文件,以确保读取操作完成,可以使用文件流中的
close()函数。
示例代码:
#include <iostream>
#include <fstream>
using namespace std;
class Person {
public:
string name;
int age;
};
int main() {
Person people[3];
ifstream inFile("people.dat", ios::in | ios::binary);
if (!inFile.is_open()) {
cout << "Open file failed." << endl;
return -1;
}
inFile.read((char*)people, sizeof(people));
inFile.close();
for (int i = 0; i < 3; i++) {
cout << "name: " << people[i].name << ", age: " << people[i].age << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/ouNL 著作权归作者所有。请勿转载和采集!