I am currently trying to read in names from an input file. The file is a .dat file.
I can read in the data using:
student_struct s;
string fileName;
fstream inFile;
inFile.open(fileName, ios::in | ios::binary);
inFile.read(reinterpret_cast<char*>(&s),sizeof(Student));
This all works fine… But I dont know how to use the data read in. I realize this is a very novice question. But I just want to read in the name from the input file and store it in another string. How do i do this?
Reading your file this way will work only for struct having no pointers at all – just plain variable types. That means you can not store even a table there (eg. char *). If your Student structure is more complex, you should have some kind of protocol saying how is your file organized. For example, you can use one or two bytes which would contain string size.
Let’s say we have the following:
Now when we want to write this to a file we can do
And to load
Of course this code doesn’t contain any error handling, which always should be performed for any I/O actions.