类中内容读入到文件
时间: 2023-12-02 09:03:39 浏览: 28
将类中的内容读入到文件中,可以使用文件流(fstream)来实现。具体步骤如下:
1. 打开一个文件流,以读写模式打开文件。
2. 将类中的内容写入文件流中。
3. 关闭文件流。
下面是一个示例代码,假设我们有一个类 Student,需要将其对象的内容写入文件中:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Student {
public:
Student(string name, int age) : m_name(name), m_age(age) {}
void writeToFile(ofstream& ofs) const {
ofs << m_name << endl;
ofs << m_age << endl;
}
static Student readFromFile(ifstream& ifs) {
string name;
int age;
ifs >> name >> age;
return Student(name, age);
}
private:
string m_name;
int m_age;
};
int main() {
Student s1("Tom", 18);
Student s2("Jack", 20);
// 打开文件流
fstream fs("data.txt", ios::out | ios::in);
// 写入对象内容到文件流
s1.writeToFile(fs);
s2.writeToFile(fs);
// 将文件指针移动到文件开头
fs.seekg(0);
// 从文件流中读取对象内容
Student s3 = Student::readFromFile(fs);
Student s4 = Student::readFromFile(fs);
// 输出读取的对象内容
cout << "s3: " << s3.name() << " " << s3.age() << endl;
cout << "s4: " << s4.name() << " " << s4.age() << endl;
// 关闭文件流
fs.close();
return 0;
}
```
上述代码中,我们在 Student 类中定义了一个 writeToFile 方法,用于将对象内容写入文件流中;同时定义了一个静态的 readFromFile 方法,用于从文件流中读取对象内容。在主函数中,我们创建了两个 Student 对象 s1 和 s2,并将它们的内容写入文件流中。然后,我们将文件指针移动到文件开头,从文件流中读取两个 Student 对象 s3 和 s4,并输出它们的内容。
需要注意的是,在打开文件流时需要指定读写模式(ios::out | ios::in),否则文件流默认为只读模式,无法写入数据。另外,对于读取文件流中的内容,我们可以使用文件指针来移动文件流中的位置。在上述代码中,我们使用了 seekg(0) 将文件指针移动到文件开头。