C++中怎么使用read()读取结构体数组
在C++中,可以使用read()函数从文件中读取结构体数组。下面是一个示例代码:
#include <iostream>#include <fstream>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;return 1;}infile.read(reinterpret_cast<char*>(students), sizeof(Student)*numStudents);for (int i = 0; i < numStudents; i++) {cout << "Student " << i+1 << ": " << students[i].name << ", " << students[i].age << " years old" << endl;}infile.close();return 0;}
在此示例中,首先定义了一个包含学生姓名和年龄的结构体Student。然后在main函数中定义了一个包含3个学生的数组students。接着打开一个名为"students.txt"的二进制文件,并使用read()函数从文件中读取结构体数组。最后,遍历数组并输出每个学生的姓名和年龄。
注意:在使用read()函数时,需要将结构体数组强制转换为char*类型,以便与read()函数的参数匹配。
上一篇:c++中的read函数怎么使用
下一篇:Lua中怎么声明和赋值变量
c++
winlogins.exe是什么文件?winlogins.exe是不是病毒
winsock2.6.exe是什么文件?winsock2.6.exe是不是病毒
WinDefendor.dll是什么文件?WinDefendor.dll是不是病毒
系统目录是什么文件?系统目录是不是病毒
wholove.exe是什么文件?wholove.exe是不是病毒
winn.ini是什么文件?winn.ini是不是病毒
w6oou.dll是什么文件?w6oou.dll是不是病毒
winduxzawb.exe是什么文件?winduxzawb.exe是不是病毒
wuammgr32.exe是什么文件?wuammgr32.exe是不是病毒
windiws.exe是什么文件?windiws.exe是不是病毒