Problem with binary file access

Hello,
I have a problem I can't find any reason for:
I have to write an 3 dimensional unsigned char array to file and read it again later.
I did this so:
writing:
1
2
3
std::fstream file("world.world",std::ios::out|std::ios::binary);
        file.write((const char*)world,sizeof(world));
        file.close();

reading:
1
2
3
4
std::fstream file("world.world",std::ios::in|std::ios::binary);
        unsigned char world[1][3][3];
        file.read((char*)world,sizeof(world));
        file.close();^

world is always defined as unsigned char world[1][3][3]
but later the three sizes should also be writen to the file, they are of type unsigned short

The problem is, at runtime the programm reads other values that it saved.
I don't have any Idea why.
I think the error is at the write because if I view the generated file with an hex editor theres always the same even if I change the values in world.
But there must also been an error in the read function because I get the same values even if I change the file itself
Last edited on
I would read and write unsigned shorts and convert them to/from chars as needed.
how exactly would your do ?
example?
this would also mean that the resulting file will be much bigger because I have to write always to bytes instead of one.
Why should this be better ?
Why are you casting an unsigned char as a char? This may be causing your problem as would certainly result in getting values you don't expect.
because the function fstream::read does not directly accept an unsigned char
It's running now.
It's not the best way but its working.
I did it using an for call now.
its not the best but its good enough for what I want to do.
Thanks for your help.
But the question is still here, how to write an unsigned char array to an file only with one fstream call?

oh right that's fstream for you ... well just cast it as char into fstream then recast it back into unsigned char. The underlying binary should stay intact.
Topic archived. No new replies allowed.