Archived

This topic is now archived and is closed to further replies.

file input and output in c++

This topic is 5315 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Im using ifstream to try to read som data from a file into two diffrent classes. I open the file with ifstream infile(filename,ios::binary) then I read infile.read((char*)class1,sizeof(class1)) then I read in the second data infile.read((char*)class2,sizeof(class2)) now the data for class2 is stored after the data for class1, that is it''s not the same data for both the class. Im guessing the problem is that the second read reads the same info as in the first read command even though the classes look diffrent. So what i wonder is how i solve this problem.

Share this post


Link to post
Share on other sites
Actually I do not even understand your problem.
But I wouldn''t read in actual objects anyway because this can AFAIK lead to lots of errors.
Try writing a struct that contains all the information you need and write/read it to a file instead of the objects.

Share this post


Link to post
Share on other sites
Ego you never even stated what your problem is. Is it crashing? Is nothing being read in? Is the wrong data being read in?

And post some real code. Are class1 and class2 supposed to be pointers or actual object instances?

Hippokrates: There are no real differences between structs and classes, nothing that would affect file I/O anyway.

Share this post


Link to post
Share on other sites
infile.read((char*)&class1,sizeof(class1));
infile.read((char*)&class2,sizeof(class2));

Does this make a difference? Unless class1 and class2 are pointers, the &-operator should be used, I THINK!

[EDIT]

If that didn't do it, use this:
infile.read((char*)&class1,sizeof(class1));
inFile.seekg( sizeof(class1), ios::beg );
infile.read((char*)&class2,sizeof(class2));

It will seek to the point after the last byte of class1.



.lick


[edited by - Pipo DeClown on May 29, 2003 10:37:01 AM]

Share this post


Link to post
Share on other sites