Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将结构写入二进制文件并读取它 我在Linux中编写了一个C++程序,其中有一个结构,名为list: struct list{ char names[20][20]; int prices[20]; int Num_Of_Merchandise; };_C++_File_Struct - Fatal编程技术网

将结构写入二进制文件并读取它 我在Linux中编写了一个C++程序,其中有一个结构,名为list: struct list{ char names[20][20]; int prices[20]; int Num_Of_Merchandise; };

将结构写入二进制文件并读取它 我在Linux中编写了一个C++程序,其中有一个结构,名为list: struct list{ char names[20][20]; int prices[20]; int Num_Of_Merchandise; };,c++,file,struct,C++,File,Struct,我创建一个结构并初始化它的数组和整数,然后将其写入一个文件。之后,我再次阅读了结构并做了一些更改: 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-rem

我创建一个结构并初始化它的数组和整数,然后将其写入一个文件。之后,我再次阅读了结构并做了一些更改:

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++;
}
列出新的\u列表;
ifstream ml(“桌面:\\Mlist.dat”,ios::in | ios::binary);
如果(毫升){
ml.read(重新解释演员表和新演员表),sizeof(新演员表);
}   
int m,i;
coutm;
如果(m==1){
cout>new_list.name[新_list.Num_商品];
cout>newPrice;
新商品清单价格[新商品清单数量]=新价格;
新列表。商品的数量++;
}
但是,当我在另一个程序中读取文件时(在更改之后),它给出了分段错误。为什么?我做错了什么

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

您的示例代码只显示读取,而不显示写入-因此您的midifications不会持久化

如果你有一个正在编写的代码,那么在没有看到你的
另一个程序的情况下就很难判断。如果您遵守其文件格式规范,那么我只能建议您确保对齐不是问题,为此,请添加
#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)
但是,当我在另一个程序中读取文件时(在更改之后),它给出了分段错误

您的示例代码只显示读取,而不显示写入-因此您的midifications不会持久化

如果你有一个正在编写的代码,那么在没有看到你的
另一个程序的情况下就很难判断。如果您遵守其文件格式规范,那么我只能建议您确保对齐不是问题,为此,请添加
#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)

因此,值得注意的是,我们也需要看到代码编写出来。我怀疑编译器正在做一些魔术,使你的数组数组工作。此外,您还不能确保文件中的二进制数据与Stutt的布局和比特度相匹配。我可以建议您查看Booo::序列化吗?也可以考虑使用谷歌PrimBufFo来正确地序列化二进制结构。这意味着用已知的endianness、size以及字符串、字符编码和字符串结尾写出每个成员。因此值得注意的是,我们也需要看到代码写出。我怀疑编译器正在做一些魔术,使你的数组数组工作。此外,您还不能确保文件中的二进制数据与Stutt的布局和比特度相匹配。我可以建议您查看Booo::序列化吗?也可以考虑使用谷歌PrimBufFo来正确地序列化二进制结构。这意味着用已知的尾数、大小以及字符串、字符编码和字符串结尾写出每个成员。