0
我写在Linux下C++程序中,我有一个结构命名列表:写一个结构二进制文件和阅读它
struct list{
char names[20][20];
int prices[20];
int Num_Of_Merchandise;
};
我做一个结构和初始化它的阵列和整数,然后我把它写入一个文件。从那以后,我再次读取结构做出了一些更改:
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++;
}
但是当我在另一个程序(更改后)读取文件,它给分段错误。为什么?我究竟做错了什么?
所以这是值得一提的我们需要看到代码也写出来。我怀疑编译器正在做一些魔术来使你的数组阵列起作用。此外,您不确定文件中的二进制数据是否与结构的布局和位数相匹配。 – Mgetz
我可以建议你看看boost :: serialization? – UKMonkey
另外,请考虑使用Google Protobuf – alexeykuzmin0