有 6 个学生数据,要求如下: 1 把六个学生数据存到磁盘文件中 2 将磁盘文件中的第 1, 2, 6 个学生数据读入程序,并显示出来。 3 将第 4 个学生数据修改后存回磁盘文件中的原有位置 4 从磁盘文件中读入修改后的 6 个学生数据并显示出来
时间: 2024-04-17 13:27:22 浏览: 42
你可以使用以下代码来实现对学生数据的存储和读取:
```
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 学生结构体
struct Student {
string name;
int age;
string major;
};
// 存储学生数据到磁盘文件
void saveToFile(string filename, Student students[], int size) {
ofstream file(filename);
if (!file) {
cout << "文件打开失败!" << endl;
return;
}
for (int i = 0; i < size; i++) {
file << students[i].name << " " << students[i].age << " " << students[i].major << endl;
}
file.close();
cout << "学生数据已保存到文件中!" << endl;
}
// 从磁盘文件中读取学生数据并显示
void readFromFile(string filename, int indices[], int size) {
ifstream file(filename);
if (!file) {
cout << "文件打开失败!" << endl;
return;
}
Student student;
int currentIndex = 1;
while (file >> student.name >> student.age >> student.major) {
for (int i = 0; i < size; i++) {
if (currentIndex == indices[i]) {
cout << "学生姓名:" << student.name << endl;
cout << "学生年龄:" << student.age << endl;
cout << "学生专业:" << student.major << endl;
cout << endl;
break;
}
}
currentIndex++;
}
file.close();
}
// 修改并存回磁盘文件中的原有位置
void updateAndSave(string filename, int index, Student updatedStudent) {
fstream file(filename);
if (!file) {
cout << "文件打开失败!" << endl;
return;
}
// 定位到指定位置
file.seekp((index - 1) * sizeof(Student));
// 写入更新后的学生数据
file << updatedStudent.name << " " << updatedStudent.age << " " << updatedStudent.major << endl;
file.close();
cout << "学生数据已更新并保存到文件中!" << endl;
}
int main() {
string filename = "students.txt";
Student students[6] = {
{"张三", 20, "计算机科学"},
{"李四", 21, "电子工程"},
{"王五", 19, "数学"},
{"赵六", 22, "物理"},
{"钱七", 18, "化学"},
{"孙八", 23, "生物"}
};
// 存储学生数据到磁盘文件
saveToFile(filename, students, 6);
// 定义要读取的学生数据的索引
int indices[3] = {1, 2, 6};
// 从磁盘文件中读取指定学生数据并显示
cout << "读取磁盘文件中的第1、2、6个学生数据:" << endl;
readFromFile(filename, indices, 3);
cout << endl;
// 修改第4个学生数据并存回磁盘文件中的原有位置
int updatedIndex = 4;
Student updatedStudent = {"赵四", 23, "化学"};
updateAndSave(filename, updatedIndex, updatedStudent);
// 从磁盘文件中读取修改后的所有学生数据并显示
cout << "读取磁盘文件中的所有学生数据:" << endl;
int allIndices[6] = {1, 2, 3, 4, 5, 6};
readFromFile(filename, allIndices, 6);
return 0;
}
```
这段代码定义了一个`Student`结构体,包含学生的姓名、年龄和专业。然后,通过`saveToFile`函数将学生数据存储到磁盘文件中。接着,通过`readFromFile`函数从磁盘文件中读取指定学生数据并显示出来。然后,通过`updateAndSave`函数对第4个学生数据进行修改,并将修改后的数据存回磁盘文件中的原有位置。最后,在主程序中,我们分别调用这些函数来完成要求的操作。记得将文件名修改为你想要操作的文件名。
阅读全文