I would like to write a function which takes an fstream, processes it, and fills information in a struct I supply in the second argument.
My problem is that I am confused how to use pointers and fstreams as I get debug errors:
Access violation writing location
0xcccccccc.
Here is the main function:
int main()
{
keyframe_struct kfstruct;
string ifile = "filename";
ifstream fin( ifile, ios::binary );
load_from_keyframe_file( fin, kfstruct );
fin.close();
cout << kfstruct.num_keyframes << endl;
return 0;
}
And here is the function I try to use for parsing the binary file and filling in the information in the struct kfstruct:
struct keyframe_struct
{
int num_views;
int num_keyframes;
vector<keyframe> keyframes;
};
int load_from_keyframe_file( ifstream &fin, keyframe_struct &kfstruct )
{
char keyword[100];
while ( !fin.eof() )
{
fin.getline( keyword, 100, 0 );
if ( strcmp( keyword, "views" ) == 0 )
{
fin.read(( char* ) kfstruct.num_views, sizeof( int ) );
}
else if ( strcmp( keyword, "keyframes" ) == 0 )
{
fin.read(( char* ) kfstruct.num_keyframes, sizeof( int ) );
}
}
}
Can you tell me what am I doing wrong? I’m sure I am making some huge errors here as I am just a beginner and I still don’t understand clearly what should I and what should I not do with pointers.
You forgot to take the address of your fields:
[As an aside, note that it’s better from a maintenance point of view to do
sizeof(kfstruct.num_views). So if the type ever changes, your code will still work.]