可以使用c++给我演示一遍吗
时间: 2024-01-07 21:04:46 浏览: 22
当然可以,下面是使用 C++ 实现题目要求的代码:
```cpp
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct Course {
char name[20]; // 课程名称
int num; // 选课人数
};
int main() {
// 读取 course.txt 文件
ifstream fin("course.txt");
if (!fin.is_open()) {
cout << "Open file failed." << endl;
return 0;
}
Course courses[5];
int i = 0;
while (fin >> courses[i].name >> courses[i].num) {
i++;
}
fin.close();
// 写入二进制文件 Course2.dat
ofstream fout("Course2.dat", ios::binary);
if (!fout.is_open()) {
cout << "Open file failed." << endl;
return 0;
}
fout.write((char *)courses, sizeof(Course) * 5);
fout.close();
return 0;
}
```
上述代码中,我们使用 C++ 的文件流实现了读取文件和写入二进制文件的功能。具体来说,我们首先打开文件 course.txt,并将其内容读取到 Course 类型的数组 courses 中,然后再打开二进制文件 Course2.dat,并将 courses 数组的内容写入到该文件中。最后,关闭文件,完成任务。