c++输入一个文件名,程序查找是否存在这个二进制文件,若不存在则新建一个此名字的二进制数据文件,若已存在,则打开文件,将数据读取并输出,然后输入学生学号和成绩,停止输入后将所有成绩显示出来并存入二进制文件中
时间: 2023-11-27 16:04:15 浏览: 25
好的,这个问题需要使用C++的文件操作来实现。以下是一个可能的实现方式:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Student {
int id;
int score;
};
int main() {
string filename;
cout << "请输入文件名:";
cin >> filename;
// 判断文件是否存在
ifstream in_file(filename, ios::binary);
if (!in_file) {
// 文件不存在,创建新文件
ofstream out_file(filename, ios::binary);
if (!out_file) {
cerr << "无法创建文件!" << endl;
return -1;
}
out_file.close();
cout << "创建新文件成功!" << endl;
}
else {
// 文件存在,读取并输出数据
in_file.seekg(0, ios::end);
int file_size = in_file.tellg();
int student_count = file_size / sizeof(Student);
in_file.seekg(0, ios::beg);
cout << "文件中包含 " << student_count << " 条记录:" << endl;
Student student;
for (int i = 0; i < student_count; i++) {
in_file.read((char*)&student, sizeof(Student));
cout << "学号:" << student.id << ",成绩:" << student.score << endl;
}
in_file.close();
}
// 输入新数据,并写入文件
ofstream out_file(filename, ios::binary | ios::app);
if (!out_file) {
cerr << "无法打开文件!" << endl;
return -1;
}
cout << "请输入学生学号和成绩,以空格分隔:" << endl;
int id, score;
while (cin >> id >> score) {
Student student = { id, score };
out_file.write((char*)&student, sizeof(Student));
}
out_file.close();
// 读取并输出所有数据
ifstream final_file(filename, ios::binary);
if (!final_file) {
cerr << "无法打开文件!" << endl;
return -1;
}
final_file.seekg(0, ios::end);
int final_size = final_file.tellg();
int final_count = final_size / sizeof(Student);
final_file.seekg(0, ios::beg);
cout << "最终文件中包含 " << final_count << " 条记录:" << endl;
Student final_student;
for (int i = 0; i < final_count; i++) {
final_file.read((char*)&final_student, sizeof(Student));
cout << "学号:" << final_student.id << ",成绩:" << final_student.score << endl;
}
final_file.close();
return 0;
}
```
这个程序首先让用户输入文件名,然后尝试打开该文件。如果文件不存在,则创建一个新文件;如果文件已存在,则读取其中的数据并输出。接着,程序要求输入学生的学号和成绩,每输入一次就将数据写入文件中。最后,程序再次读取文件中的所有数据并输出。请注意,在写入数据和读取数据时,我们都使用了 `ios::binary` 标志,以便正确处理二进制数据。