2017-01-27 75 views
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++; 
} 

但是当我在另一个程序(更改后)读取文件,它给分段错误。为什么?我究竟做错了什么?

+0

所以这是值得一提的我们需要看到代码也写出来。我怀疑编译器正在做一些魔术来使你的数组​​阵列起作用。此外,您不确定文件中的二进制数据是否与结构的布局和位数相匹配。 – Mgetz

+0

我可以建议你看看boost :: serialization? – UKMonkey

+0

另外,请考虑使用Google Protobuf – alexeykuzmin0

回答

0

但是,当我在另一个程序(更改后)读取文件时,它给出了分段错误。

你的示例代码只显示阅读,没有写入 - 所以你的midifications不会被持久化。

如果您有书写代码,那么很难说没有看到您的another program代码。如果你坚持它的文件格式规范,那么我只能推荐将确保比对是不是一个问题在这里,要做到这一点添加#pragma pack,这将在两个MSVC工作和GCC:

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