Writing large values to a file
Ok folks, my brain must be completely asleep today because this one is stumping me big-time...
I have a function that writes out 83 bytes of information for my game. All of the data, except for six fields, are unsigned char's (simple flags and options, a couple of coordinates that are always 0-255, etc). I have a buffer defined as...
unsigned char* outBuffer = (unsigned char*)malloc(83);
...that I put all the data into, then write it out. It works perfectly well for just about all of the data I'm working with, no problem.
However, the six fields I alluded to are DWORD variables, so of course that's the equivalent of 4 unsigned char's.
Here's my question... how do I write them out to my file (really, how do I insert them into my buffer) without losing precision? The code I'm using for the other fields is basically:
int indexer = 0;
*(outBuffer + indexer++) = (unsigned char)volumeLevel;
*(outBuffer + indexer++) = (unsigned char)currentGameLevel;
// ... and so on...
...for the most part the casts aren't necassery, but since some of the variables are actualy ints (that are always in the range of an unsigned char anyway), I do it all the time just to be safe. I of course can't just casts a DWORD to an unsigned char because I'd lose information.
So, I guess another way of asking this is how can I break a DWORD into the four bytes that make it up, write them out, and then re-constitute the four bytes into a DWORD when I read the file back in?
TIA!
I don't really know what you want to know but here some ideas...
1 - if you want to save it to a file, you can just use fwrite for each char.
2 - but another way to put it into a buffer would be using shift to store values:
- Code:
DWORD store(char val1, char val2, char val3, char val4)
{
DWORD retVal = 0;
retVal |= val1 << 24;
retVal |= val2 << 16;
retVal |= val3 << 8;
retVal |= val4 << 0;
return retVal;
}
3 - using a struct could be interesting too. Just have to cast it into a DWORD :P
- Code:
typedef struct _MyDWORD
{
char data[4];
} MyDWORD;
Hmm... the shifting feels close to what I want to do... let me try that...
I generally like to use structures to take care of a lotta variables all at once.
- Code:
typedef struct _MyBuffer
{
unsigned char volumeLevel;
DWORD gameLevel;
TCHAR myName[27];
bool bDead;
...
} MyBuffer;
FILE *stream;
MyBuffer *buffer;
buffer = (MyBuffer *) malloc( sizeof( MyBuffer ) );
fread( buffer, 1, sizeof( MyBuffer ), stream);
fclose(stream);
// Do work now that buffer->gameLevel, etc are filled in
free(buffer);
JJB
JongJungBu, is that portable between desktop and PPC? I remember certain functions weren't available on PPC, but I don't recall which. If it is, I would take the time to re-write my code to work this way, that is a far clearer way of doing things.
that's a really good approache (I use that often also). But there is some problem using that method sometime. For example, if you send data between 2 devices that are not the same (endianness, of just different internal data structures). Another problem is if you have something like that:
- Code:
struct {
int i;
char c;
float f;
bool b
}
you don't know the size that will take and how the compiler will put the data internally... maybe the compiler will use 16 bytes and you want to use only 12 bytes. For some cases, it's better to do it manually.
edit ---
you are absolutely right about that... you just reply faster than me :P
You are right about the different endianess problem and the varying sizes of data types on different platforms. I really haven't had much of a problem with this for PPC-PC programs. It has come up before though, in which case I ended up using #ifdef's for certain reads for the alternate data size. And of course you have to take care of TCHAR factors since sometimes the PC can treat a TCHAR as a char or as an unsigned short.
But in general, particularly the various integer types, I haven't had any problems for portability from PPC to PC and back. Oh and I generally use _tfopen as opposed to fopen. But aside from that, I don't see any functions in what I posted that I haven't used in both evC and visual studio.
Another thing I do is avoid using 'int' explicitly as a data type since that has been documented as varying in size. At least for variables that I intend to fwrite. Thusly I often use long or short etc, or have typedefs for 8-,16-,and 32-bit integers so that I can get some form of consistency in size.
JJB
Yes, it seems to do the trick for me too. I found the _tfopen function too. I suppose this all only really becomes and issue if you want to transfer files from platform to platform. I mean, if I write an int out on a given device, and I read it back in later, I don't see how it's endedness matters, or what actually gets written, or what the size of an int is (assuming it wouldn't matter otherwise of course). As long as the value of my int after I read it back in matches the int I wrote out, the rest I don't hink matters much.
Thanks guys, that made my code a lot easier to look at!
Well size can matter if you read and write the same data on different platforms, but evC + Windows CE and visual studio + Windows XP are pretty compatible. Their data type sizes are pretty much congruous. You can look up the sizes for the various data types as I did before I started trying to port. It will not matter what PPC device you use, if you look up the MSDN for it you'll see that char is 1 byte, long is 4 bytes and so forth for PPCs. Which pretty much matches up to what youll see for your PC versions.
Now, if yer headin off into Macs, Palm, and Linux ports then you may see some problemos. But just PC and PPC only it should all match up just fine, minus TCHAR issues. I have created data files that were read fine on both PC and PPC and created on opposite machines.
Hope that rambling helps.
JJB
I never think about the data in memory, but instead worry about its format on disk. On disk, it will have a particular file format. That is the protocol. You can always change the format in memory, so long as it matches the format on disk.
An example you gave, is storing a char, which came from an int in memory. The char is the protocol, the int is just an implementation detail.
Having defined my protocol, I just use fwrite to write my file out in my protocol. This is easy if you make a few functions, like writeInt, writeChar, writeIntAsChar, etc.
I typically write ints as four bytes using fwrite. But sometimes I write them a char at a time, using shifts. Both described above.
Since this is my file format, porting to Palms etc. is simple: they must follow my file format. So Palms have a different endianness... it is the Palm port's responsibility to swap endianness before writing and after reading. This is by (my) definition.
You see, it sounds above like some people are worrying about the code, the format in memory, and porting. I don't worry about that, because it's easy to change. It's the file format I worry about. (Or the network protocol, or whatever.) Then I make the code conform to the protocol, whatever changes that requires.
mlepage has the idea :) For my part, I use a class of my own: FileStream that has member like WriteChar, ReadChar, etc...
But for faster result on palm mlepage, you should change your rule: converting the endianess on palm will be a lot slower than PC :)
Well, all the theory aside, the bottom line is that the code worked, so I am happy. I did away with the whole malloc/free portion of it though as I prefer to avoid manual allocations as much as possible. I also try avoiding the -> operator wherever possible. I think it makes for ugly code. Not that any of that is relevant... It works fine on desktop and PPC, I'm not worried about Palm for now, so all is well. Thanks again guys!
Let me share a professional endianness story.
I was working on some file reading/writing code, porting it from Windows to PC. It already ran on Windows, but was originally Mac code.
Anyways, the Windows programmers had been careful to do byte swapping to put the file's contents into big endian byte order. This was new code, but they wanted to remain compatible with all the other code, which was big endian because of its Mac heritage.
Well, when porting this code, and wondering why it didn't work, I discovered that they screwed up the byte swapping. In the end, it was writing out a mixed endian byte order, which was neither big nor little endian.
This wasn't discovered on the Mac, because that particular piece of code wasn't part of the Mac build. It wasn't discovered on Windows, because frankly they were not very careful at catching things like this. I had to make this work on various Unix flavours, replicating whatever funky byte swapping they were mistakenly doing on Windows.
Anyways, the moral of this story is to always test your data, don't just look at your code and say "yeah that looks OK" but actually open the file and verify that its contents are what you expect.
You might wanna use
#pragma pack(1)
UNALIGNED struct BLAH
{
...
} blahblah;
#pragma pack()
pragma pack(1) makes sure it's packed on byte boundaries, not dword/etc boundaries.
The UNALIGNED macro makes sure access to this struct will be unligned access. It's important on CE devices, otherwise you get a data misalignment error, as the processor can only read whole dwords on 4 byte boundaries.
Cheers,
Peter