#include<iostream> #include<fstream> using namespace std; class Student { public: int num; char name[20]; }; int main() { fstream iofile("File.txt", ios::in | ios::out | ios::binary); if (!iofile) { cout << "打开失败" << endl; exit(1); } Student st[2] = { {101 ,"Tom"},{102,"Bob"} }, stunew[2]; for (int i = 0; i < 2; i++) { iofile.write((char*)&st[i], sizeof(Student)); } for (int i = 0; i < 2; i++) { iofile.seekg(i * sizeof(st[i]), ios::beg); iofile.read((char*)&stunew[i], sizeof(Student)); } strcpy(stunew[1].name, "Lux"); stunew[1].num = 103; iofile.seekp(sizeof(st[0]), ios::beg); iofile.write((char*)&stunew[1], sizeof(Student)); iofile.seekg(0, ios::beg); for (int i = 0; i < 2; i++) { iofile.read((char*)&stunew[i], sizeof(Student)); cout << "第" << i + 1 << "个同学的信息:" << stunew[i].name << ":" << stunew[i].num << endl; } iofile.close(); }代码为什么运行错误
时间: 2023-06-25 07:06:51 浏览: 153
你的代码运行错误的原因是,你在写入文件时使用了 `ios::binary` 标志,但在读取文件时没有使用该标志。这会导致在 Windows 系统上读取二进制文件时出现问题。
为了解决这个问题,你需要在读取文件时也使用 `ios::binary` 标志,像这样:
```
iofile.seekg(i * sizeof(st[i]), ios::beg);
iofile.read((char*)&stunew[i], sizeof(Student));
```
修改后的完整代码如下:
```
#include<iostream>
#include<fstream>
using namespace std;
class Student {
public:
int num;
char name[20];
};
int main() {
fstream iofile("File.txt", ios::in | ios::out | ios::binary);
if (!iofile)
{
cout << "打开失败" << endl;
exit(1);
}
Student st[2] = { {101 ,"Tom"},{102,"Bob"} }, stunew[2];
for (int i = 0; i < 2; i++)
{
iofile.write((char*)&st[i], sizeof(Student));
}
for (int i = 0; i < 2; i++)
{
iofile.seekg(i * sizeof(st[i]), ios::beg);
iofile.read((char*)&stunew[i], sizeof(Student));
}
strcpy(stunew[1].name, "Lux");
stunew[1].num = 103;
iofile.seekp(sizeof(st[0]), ios::beg);
iofile.write((char*)&stunew[1], sizeof(Student));
iofile.seekg(0, ios::beg);
for (int i = 0; i < 2; i++)
{
iofile.read((char*)&stunew[i], sizeof(Student));
cout << "第" << i + 1 << "个同学的信息:" << stunew[i].name << ":" << stunew[i].num << endl;
}
iofile.close();
return 0;
}
```
阅读全文