C++ - Noob Binary File IO question
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 j开发者_开发技巧ust 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:
struct Student
{
std::string name;
int some_id;
std::string hair_color_description;
};
Now when we want to write this to a file we can do
void saveToFile( Student s, fstream& f )
{
size_t strSize = s.name.size();
f.write( reinterpret_cast<char*>( &strSize ), sizeof(size_t) );
f.write( reinterpret_cast<char*>( s.name.data() ), strSize );
f.write( reinterpret_cast<char*>( &s.some_id ), sizeof(int) );
strSize = s.hair_color_description.size();
f.write( reinterpret_cast<char*>( &strSize ), sizeof(size_t) );
f.write( reinterpret_cast<char*>( s.hair_color_description.data() ), strSize );
}
And to load
void loadFromFile( Student& s, fstream& f )
{
char *buffer = NULL;
size_t strSize;
f.read( reinterpret_cast<char*>( &strSize ), sizeof(size_t) );
buffer = new char[strSize];
f.read( buffer, strSize );
s.name = buffer;
delete[] buffer;
f.read( reinterpret_cast<char*>( &s.some_id ), sizeof(int) );
f.read( reinterpret_cast<char*>( &strSize ), sizeof(size_t) );
buffer = new char[strSize];
f.read( buffer, strSize );
s.hair_color_description = buffer;
delete[] buffer;
}
Of course this code doesn't contain any error handling, which always should be performed for any I/O actions.
For you to use the struct that means you have defined in a header file or somewhere before getting to this code right?
If that is the case then you are storing the data in "s" and if you defined the struct as:
student_struct { char firstname[FIRST_NAME_LEN]; char lastname[LAST_NAME_LEN]; };
Then to access it you use s.firstname;
and s.lastname
since you are reading it from a file you might want to use a while loop and read until end of file.
精彩评论