For the sake of simplicity I wrote a simple code to reproduce my problem. As you can see on the code i created a struct with two members then I created and array of the struct type then initialized it student newStudent[3] ={{"joseph",20}, {"yonas",30},{"miryam",40}};. I stored all the info from the struct to a binary file newFile.write(reinterpret_cast<char*>(newStudent), 3 * sizeof(student));(everything is fine until here) then i created another array student loadedStudent[3]; to load into, all the data from the binary file and output the loaded data using a for loop cout<<"Name: "<<loadedStudent[i].name<<"Age: "<<loadedStudent[i].age<<endl;. The problem is that the data i stored is joseph",20, "yonas",30,"miryam",40 but the program is outputting garbage values Name: 8H???Age: 1 Name: J???Age: 1 Name: ?I???Age: 32766.
Why is that?
#include <iostream>
#include <fstream>
using namespace std;
struct student{
char name[10];
int age;
};
int main()
{
student newStudent[3] ={{"joseph",20}, {"yonas",30},{"miryam",40}};
fstream newFile;
newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::binary);
//for(int i = 0; i<3; i ){
//cout<<"Name: "<<newStudent[i].name<<" Age: "<<newStudent[i].age<<endl;
//}
if(newFile.is_open()){
newFile.write(reinterpret_cast<char*>(newStudent), 3 * sizeof(student));
}else cout<<"faild to open file";
student loadedStudent[3];
newFile.seekg(0, ios::beg);
if(newFile.is_open()){
newFile.read(reinterpret_cast<char*>(loadedStudent), 3 * sizeof(student));
newFile.close();
}else cout<<"faild to open file";
for(int i = 0; i<3; i ){
cout<<"Name: "<<loadedStudent[i].name<<"Age: "<<loadedStudent[i].age<<endl;
}
CodePudding user response:
When you opened the file you only opened it as output ios::out you shoul've also included ios::in so you can access the file. Now you're printing the indeterminate values of an uninitialized array.
change this
newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::binary);
into
newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::in | ios::binary);
CodePudding user response:
newFile.open("/Users/josephfeleke/Desktop/abeltest/file.bin", ios::out | ios::binary);
This is opening the file for output only. You need ios::in | ios::out to be able to both read and write.
