c++ 存 读结构体

#include
#include 

using namespace std;
struct SalaryInfo{
    unsigned id;
    double salary;
    int ranges[500];
};
int main(){
    SalaryInfo employee1 ={600001, 8000};
        employee1.ranges[3] = 4;
        employee1.ranges[13] = 44;
    ofstream os("payroll", ios_base::out | ios_base::binary);
    os.write(reinterpret_cast( &employee1), sizeof(employee1) );
    os.close();
    ifstream is("payroll", ios_base::out | ios_base::binary);
    string s;
    getline(is, s);
    is.close();
    char *data;
    int len = s.length();
    data = (char *)malloc((len+1)*sizeof(char));
    s.copy(data,len,0);
    SalaryInfo *employee2 = (SalaryInfo *) data;
    std::cout << employee2->id << std::endl;
    std::cout << employee2->ranges[3] << std::endl;
    std::cout << employee2->ranges[13] << std::endl;
    return 0;
}

你可能感兴趣的:(c++ 存 读结构体)