cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
struct Student {
std::string name;
int studentID;
int age;
};
using namespace std;
void writeStudentsToFile(const std::vector<Student>& students) {
std::ofstream outputFile("students.dat", std::ios::binary);
if (outputFile.is_open()) {
// 写入学生数量
int numStudents = students.size();
outputFile.write(reinterpret_cast<const char*>(&numStudents), sizeof(numStudents));
// 逐个写入学生信息
for (const Student& student : students) {
int nameSize = student.name.size();
outputFile.write(reinterpret_cast<const char*>(&nameSize), sizeof(nameSize));
outputFile.write(student.name.c_str(), nameSize);
outputFile.write(reinterpret_cast<const char*>(&student.studentID), sizeof(student.studentID));
outputFile.write(reinterpret_cast<const char*>(&student.age), sizeof(student.age));
}
outputFile.close();
std::cout << "学生信息已成功保存到文件。" << std::endl;
} else {
std::cout << "无法打开文件。" << std::endl;
}
}
void readStudentsFromFile(std::vector<Student>& students) {
std::ifstream inputFile("students.dat", std::ios::binary);
if (inputFile.is_open()) {
// 读取学生数量
int numStudents;
inputFile.read(reinterpret_cast<char*>(&numStudents), sizeof(numStudents));
// 逐个读取学生信息
for (int i = 0; i < numStudents; ++i) {
int nameSize;
inputFile.read(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
std::string name(nameSize, ' ');
inputFile.read(&name[0], nameSize);
int studentID;
inputFile.read(reinterpret_cast<char*>(&studentID), sizeof(studentID));
int age;
inputFile.read(reinterpret_cast<char*>(&age), sizeof(age));
students.push_back({name, studentID, age});
}
inputFile.close();
std::cout << "学生信息已成功从文件读取。" << std::endl;
} else {
std::cout << "无法打开文件。" << std::endl;
}
}
int main() {
int choice;
std::cout << "请输入选项:1 - 写入学生信息到文件;2 - 从文件读取学生信息" << std::endl;
std::cin >> choice;
vector<Student> students;
if(choice==1){
students.push_back({"张三", 1001, 20});
students.push_back({"李四", 1002, 21});
students.push_back({"爱达斯", 1003, 22});
writeStudentsToFile(students);
} else if (choice == 2) {
readStudentsFromFile(students);
// 打印读取的学生信息
for (const Student& student : students) {
std::cout << "姓名:" << student.name << std::endl;
std::cout << "学号:" << student.studentID << std::endl;
std::cout << "年龄:" << student.age << std::endl;
std::cout << std::endl;
}
} else {
std::cout << "无效的选项。" << std::endl;
}
return 0;
}