Overwriting struct in binary file
-
I have a question. I wrote and array of 5 structs into a binary file. I need to be able to go to a specific position in a binary file and overwrite that struct with another. I have tried it but when i go to overwrite the struct the ones before it all the data is screwed up.Can anyone help me on how to overwrite a specific person in the file. struct PERSON { int age; int weight; char name[25]; }; void write_names() //WRITES 5 PEOPLE TO THE FILE { ofstream out; PERSON p[5]; int ct; p[0].age = 1; p[0].weight = 1; strcpy(p[0].name, "Num_1"); p[1].age = 2; p[1].weight = 2; strcpy(p[1].name, "Num_2"); p[2].age = 3; p[2].weight = 3; strcpy(p[2].name, "Num_3"); p[3].age = 4; p[3].weight = 4; strcpy(p[3].name, "Num_4"); p[4].age = 5; p[4].weight = 5; strcpy(p[4].name, "Num_5"); out.open("file.dta", ios::binary); for (ct=0; ct<5; ct++) out.write((char*)& p[ct], sizeof(p[ct])); out.close(); } void show_names() //SHOW ALL THE PEOPLE IN THE FILE { ifstream f; f.open("file.dta", ios::binary); PERSON p[10]; int ct; int num = 0; while(!f.eof()) { f.read((char*)& p[num], sizeof(p[num])); num++; } num--; for(ct=0; ct
-
I have a question. I wrote and array of 5 structs into a binary file. I need to be able to go to a specific position in a binary file and overwrite that struct with another. I have tried it but when i go to overwrite the struct the ones before it all the data is screwed up.Can anyone help me on how to overwrite a specific person in the file. struct PERSON { int age; int weight; char name[25]; }; void write_names() //WRITES 5 PEOPLE TO THE FILE { ofstream out; PERSON p[5]; int ct; p[0].age = 1; p[0].weight = 1; strcpy(p[0].name, "Num_1"); p[1].age = 2; p[1].weight = 2; strcpy(p[1].name, "Num_2"); p[2].age = 3; p[2].weight = 3; strcpy(p[2].name, "Num_3"); p[3].age = 4; p[3].weight = 4; strcpy(p[3].name, "Num_4"); p[4].age = 5; p[4].weight = 5; strcpy(p[4].name, "Num_5"); out.open("file.dta", ios::binary); for (ct=0; ct<5; ct++) out.write((char*)& p[ct], sizeof(p[ct])); out.close(); } void show_names() //SHOW ALL THE PEOPLE IN THE FILE { ifstream f; f.open("file.dta", ios::binary); PERSON p[10]; int ct; int num = 0; while(!f.eof()) { f.read((char*)& p[num], sizeof(p[num])); num++; } num--; for(ct=0; ct
you need to use ios::binary|ios::_Nocreate as the open mode when you do the open to replace the second person