C++结构体问题,如何把一个结构体写入文件

2025-04-18 07:32:07
推荐回答(2个)
回答1:

#include
#include 

using namespace std;

struct SalaryInfo{
unsigned id;
double salary;
//char name[23];
};


int main(){
    SalaryInfo employee1 ={600001, 8000};//, "F Lei"};
ofstream os("payroll", ios_base::out | ios_base::binary);
os.write(reinterpret_cast( &employee1), sizeof(employee1) );
os.close();

    ifstream is("payroll", ios_base::in | ios_base::binary);
    if (is){
SalaryInfo employee2;
is.read(reinterpret_cast(&employee2), sizeof(employee2));
cout << employee2.id << " "<< employee2.salary <    }else{
        cout << "ERROR: Cannot open file 'payroll'." << endl;
    }
is.close();

return 0;
}

这是一个读写结构体到文件的例子

回答2:

加一个强制转换试试。
(char *)bmpHeader