c++,输入一个文件名,程序查找是否存在,若不存在,则创建新的此二进制数据文件,若存在,则输出所有数据,然后提示用户输入若干名学生的名字和学号,全部输入后将所有数据显示,并存入文件
时间: 2023-12-07 09:02:53 浏览: 39
好的,这是一个比较典型的文件操作问题,需要使用 C++ 的文件流操作。下面是一个简单的实现:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int id;
};
int main() {
string filename;
cout << "请输入文件名:";
cin >> filename;
// 判断文件是否存在
ifstream fin(filename, ios::binary);
if (fin) {
// 文件存在,读取数据
vector<Student> students;
while (true) {
Student s;
fin.read((char*)&s, sizeof(s));
if (fin.eof()) {
break;
}
students.push_back(s);
}
fin.close();
// 输出数据
for (auto s : students) {
cout << "姓名:" << s.name << ",学号:" << s.id << endl;
}
// 输入新数据
while (true) {
cout << "请输入学生姓名和学号(输入 quit 结束):";
string name;
int id;
cin >> name;
if (name == "quit") {
break;
}
cin >> id;
students.push_back({name, id});
}
// 写入数据
ofstream fout(filename, ios::binary);
for (auto s : students) {
fout.write((char*)&s, sizeof(s));
}
fout.close();
} else {
// 文件不存在,创建文件
ofstream fout(filename, ios::binary);
fout.close();
}
return 0;
}
```
这个程序首先读取用户输入的文件名,然后判断文件是否存在。如果文件存在,就读取所有数据并输出,然后提示用户输入新的数据,最后将所有数据写入文件。如果文件不存在,就创建一个空文件。
需要注意的是,这个程序使用了二进制文件流(`ios::binary`),因此结构体的读写操作需要使用 `read` 和 `write` 函数,同时需要将结构体转换为 `char*` 类型。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)