我想將我的數組結構寫入二進制文件。問題在C++中讀寫二進制文件中的結構數組
我的結構
typedef struct student{
char name[15];
vector<int> grade;
}arr_stu;
我能寫和讀回我的數據,如果我寫,並在相同的程序讀取;但如果我只爲讀取數據創建另一個程序並放入二進制文件,則它不起作用,因爲矢量等級爲空。
size = 0;
unable to read from memory
程序寫入陣列結構到文件
int main()
{
arr_stu stu[100];
for (size_t i = 0; i < 100; i++)
{
strcpy(stu[i].name, randomName());
for (size_t j = 0; j < 10; j++)
{
stu[i].grade.push_back(randomGrade());
}
}
ofstream outbal("class", ios::out | ios::binary);
if (!outbal) {
cout << "Cannot open file.\n";
return 1;
}
outbal.write((char *)&stu, sizeof(stu));
outbal.close();
}
程序讀取陣列結構到文件
int main(){
feature_struc stu[100];
ifstream inbal("class", ios::in | ios::binary);
if (!inbal) {
cout << "Cannot open file.\n";
return 1;
}
inbal.read((char *)&stu, sizeof(stu));
for (size_t idx = 0; idx < 100; idx++)
{
cout << "Name : " << stu[idx].name << endl;
for (size_t index = 0; index < 10; index++)
{
cout << endl << "test: " << stu[idx].grade[index] << endl;
}
}
inbal.close();
return 0;
}
對於我來說,好像使用矢量的姿問題, 如果我們在一個程序中合併這兩個程序,它的工作很好的原因是我t因爲矢量被保存在內存中,所以它仍然可以訪問。
有什麼建議嗎?
你不需要'typedef結構...',你也應該使用更多的'標準::矢量'以及'std :: string'而不是數組和C字符串。 – crashmstr
你必須爲此使用二進制文件?如果你想保持二進制樣式,你不能使用'XML','YAML','JSON'甚至'sqlite'嗎? –