将数据写入二进制文件并将其从文件中读出存放在结构体中

时间:2022-12-06 12:49:06

 1 #include<iostream>
 2 #include<fstream>
 3 #include<string>
 4 using namespace std;
 5 
 6 struct SalaryInfo {
 7     string id;
 8     double salary;
 9 };
10 int main() {
11     SalaryInfo employee1 = { "S600",6000.0 };
12     ofstream os("usersfile", ios_base::out | ios_base::binary);//usersfile在当前工作目录下,如果不存在则自动生成
13     os.write(reinterpret_cast<char*>(&employee1), sizeof(employee1));
14     os.close();
15     ifstream is("usersfile", ios_base::in | ios_base::binary);
16     if (is) {
17         SalaryInfo employee2;
18         is.read(reinterpret_cast<char*>(&employee2), sizeof(employee2));
19         cout << employee2.id << " " << employee2.salary;
20     }
21     else
22         cout << "ERROR:Cannot open file 'usersfile'." << endl;
23 }