/ v2.0 start ///
在 C++ 中,可以使用文件流(fstream)来实现对象的写入和读取。具体步骤如下:
写入对象到文件:
- 打开文件并创建一个输出文件流对象,用于写入数据。
- 将对象写入文件流中。
读取文件中的对象:
- 打开文件并创建一个输入文件流对象,用于读取数据。
- 从文件流中读取对象。
下面是一个示例代码,演示了如何将对象写入文件和从文件中读取对象:
#include <iostream>
#include <fstream>
// 假设有一个简单的学生类
class Student {
public:
std::string name;
int age;
// 构造函数
Student(const std::string& n, int a) : name(n), age(a) {}
// 打印学生信息
void printInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
int main() {
// 写入对象到文件
{
// 创建输出文件流对象
std::ofstream outputFile("students.txt", std::ios::binary);
// 检查文件是否成功打开
if (!outputFile) {
std::cout << "无法打开文件进行写入操作!" << std::endl;
return 1;
}
// 创建学生对象
Student student1("Alice", 20);
Student student2("Bob", 22);
// 写入学生对象到文件
outputFile.write(reinterpret_cast<char*>(&student1), sizeof(Student));
outputFile.write(reinterpret_cast<char*>(&student2), sizeof(Student));
// 关闭文件流
outputFile.close();
}
// 从文件中读取对象
{
// 创建输入文件流对象
std::ifstream inputFile("students.txt", std::ios::binary);
// 检查文件是否成功打开
if (!inputFile) {
std::cout << "无法打开文件进行读取操作!" << std::endl;
return 1;
}
// 读取学生对象
Student student3;
Student student4;
inputFile.read(reinterpret_cast<char*>(&student3), sizeof(Student));
inputFile.read(reinterpret_cast<char*>(&student4), sizeof(Student));
// 关闭文件流
inputFile.close();
// 打印读取到的学生信息
student3.printInfo();
student4.printInfo();
}
return 0;
}
上述代码中,我们通过创建 std::ofstream
和 std::ifstream
对象来进行文件的写入和读取。std::ofstream
用于输出(写入)文件流,std::ifstream
用于输入(读取)文件流。在写入时,我们使用 write
函数将对象的二进制数据写入文件流中;在读取时,我们使用 read
函数从文件流中读取二进制数据,并将其重新解释为对象。
需要注意的是,在写入和读取对象时,需要使用 reinterpret_cast
将对象的地址转换为 char*
类型的指针,这是因为对象的二进制表示需要以字节为单位进行写入和读取。
请确保在操作文件
时,文件流对象的打开和关闭操作是正确的,以避免出现意外错误。
/ v2.0 end ///
2022 -07-14 / v1.0 start /// 一、将对象写入文件
// 几何体初始化
Point p1(0, 0);
Point p2(100, 100);
Line line(p1, p2); // 线段
Circle circle(p1, 300); // 圆
Point a(0, 0); // 矩形
Point b(100, 0);
Point c(100, 100);
Point d(0, 100);
Rectangle rectangle(a,b,c,d);
//读取的时候遵循先写先读
ofstream osm("tempfile.txt", ios::out | ios::binary); // 先将文件写入tempfile.txt
osm.write((char*)&line, sizeof(Line));
osm.write((char*)&circle, sizeof(Circle));
osm.write((char*)&rectangle, sizeof(Rectangle));
osm.close();
二、从文件中读取对象
// 创建一个新的线段对象,来接收文件里读取出来的那个线段对象
Line myLine;
ifstream ism("tempfile.txt", ios::in | ios::binary);
ism.read((char*)&myLine, sizeof(Line));
/ v1.0 end ///