Is there anything obviously wrong with this open and read file code?

This code is causing different errors between the times that I run my program. It's pretty much exactly the same as the example on this websiteit.

The errors don't occur within this block of code, the errors come later in my program.

Right now as you can see the affected variable SaveFile is scoped within the if block so it doesn't seem like there should be any side effects...

'filenameLoad()' just returns the string of the filename to be opened

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using std::ios;

std::ifstream lfile;
lfile.open( filenameLoad(), ios::in|ios::binary|ios::ate );

if( lfile.is_open() )
{
    SaveFile lsavefile;
    std::ifstream::pos_type lsize = lfile.tellg();
    assert( lsize == sizeof( SaveFile ) );
    lfile.seekg( 0, ios::beg );
    lfile.read( (char*)&lsavefile, lsize );
    lfile.close();
}
What is the definition of SaveFile? If it isn't a POD struct you'll have trouble with that byte-wise reading technique.
Even a POD struct can be a problem, if it contains pointers.

To get away with saving and then reloading a struct by treating it as a byte array, all the data must be stored contiguously within the struct. So (e.g.) char arrays are in and char*s very much out.

Andy
Last edited on
Oops yep that's the problem, my SaveFile type has a text string.
Err, so what is the best way to handle mixed strings and binary data?

I think the most reasonable thing would be to write it all as text.

The only problem I have with that is if I add or remove data fields I have to manually update my read and write functions, wheras if I was writing and reading binary I just set the pointer and read/write to the end of the binary portion. It seems do-able to have text say at the beginning or end of the file and then start or end binary at a certain point.

Would it be better to split the file into two? One for text one for binary?
Topic archived. No new replies allowed.