阅读量:131
在C++中,可以使用read()函数从文件中读取结构体数组。下面是一个示例代码:
#include
#include
using namespace std;
struct Student {
string name;
int age;
};
int main() {
int numStudents = 3;
Student students[numStudents];
ifstream infile("students.txt", ios::binary);
if (!infile) {
cerr << "Error opening file" << endl class="hljs-keyword">return 1;
}
infile.read(reinterpret_cast<char*>(students), sizeof(Student)*numStudents);
for (int i = 0; i < numStudents class="hljs-string">"Student " << i class="hljs-number">1 << ": " << students class="hljs-string">", " << students class="hljs-string">" years old" << endl class="hljs-built_in">close();
return 0;
}
在此示例中,首先定义了一个包含学生姓名和年龄的结构体Student。然后在main函数中定义了一个包含3个学生的数组students。接着打开一个名为"students.txt"的二进制文件,并使用read()函数从文件中读取结构体数组。最后,遍历数组并输出每个学生的姓名和年龄。
注意:在使用read()函数时,需要将结构体数组强制转换为char*类型,以便与read()函数的参数匹配。