简体   繁体   中英

writing an structure to a binary file and reading it

I'm writing a c++ program in Linux in which I have a structure named list:

struct list{

    char names[20][20];
    int prices[20];
    int Num_Of_Merchandise;
};

I make an structure and initialize its arrays and integer, then I write it to a file. After that I read the structure again and make some changes:

list new_list;

ifstream ml("Desktop:\\Mlist.dat", ios::in | ios::binary);

if(ml){
    ml.read(reinterpret_cast<char*>(&new_list),sizeof(new_list));
}   

int m,i;
cout<<"1-add\n2-remove\n";
cin>>m;
if(m==1){
    cout<< "enter the name of new merchandise:\n";
    cin>>new_list.names[new_list.Num_Of_Merchandise];
    cout<< "enter the price of new merchandise:\n";
    int newPrice;
    cin>>newPrice;  
    new_list.prices[new_list.Num_Of_Merchandise]=newPrice;
    new_list.Num_Of_Merchandise++;
}

But then when I read the file in another program (after changes), it gives segmentation fault. Why? What am I doing wrong?

But then when I read the file in another program (after changes), it gives segmentation fault.

Your example code show only reading, there is no writing - so your midifications are not persisted.

If you have a writing code anyway then its hard to tell without seeing your another program code. If you adhere to its specification for a file format, then I can only recomend to make sure alignment is not an issue here, to do this add #pragma pack which will work on both MSVC and gcc:

#pragma pack(push)
#pragma pack(1)
struct list{
    char names[20][20];
    int prices[20];
    int Num_Of_Merchandise;
};
#pragma pack(pop)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM