So I'm writing an RLE compressor, and basically, you take the runs of a file (the continuous strings of the same byte) and convert it to a packet. For example, if the file contains: 0xFF 0xFF 0xFF 0xFF 0xBB 0xBB 0xBB you would convert it into packets, containing a length and the data: It would turn out 0x04FF 0x03BB. You get the idea.
I use a structure to define the packet. (byte is a typedefd type for an unsigned 8 bit type)
typedef struct /* Each packet has a length and a data byte */
{
byte length; /* how many elements of data there is */
byte data; /* whatever byte is being repeated */
} PACKET;
and I have my writeData function:
void writeData(FILE* f, int offset, PACKET p)
{
fseek(f,offset,SEEK_SET); /* move to the offset to write */
fwrite(&p,sizeof(PACKET),sizeof(PACKET),f); /* write the packet to the given offset */
}
And here is the code that calls the function
offsetCounter = 0x0; /* reset offset counter */
for(i = 0; i < nPackets; i++) /* nPackets is the total amount of packets created */
{
writeData(fDest,offsetCounter,packet[i]);
printf("Wrote %d:0x%X to 0x%X\n",packet[i].length,packet[i].data,offsetCounter);
offsetCounter += 0x02; /* skip 2 bytes to write the next packet */
}
When I run the program, everything works fine, and the packets are written to the file correctly, except for some reason, at the very end of the file, there are 2 0x00 bytes that are automatically added on. So, for some reason, it just adds 2 extra empty bytes.
However, when I write the writeData function like this:
void writeData(FILE* f, int offset, PACKET p)
{
fseek(f,offset,SEEK_SET);
fwrite(&p.length,sizeof(byte),sizeof(byte),f);
fwrite(&p.data,sizeof(byte),sizeof(byte),f);
}
, which writes each byte of the structure separately, it no longer adds 2 extra empty bytes to the end of the file..
I'm really confused as to why when I write the structure, it works fine, but adds 2 extra bytes at the end, but when I write each element of the structure separately, it doesn't add them.
Could somebody help me figure this out?
You have the incorrect line
fwrite(&p,sizeof(PACKET),sizeof(PACKET),f);
The structure size is 2 so you are writing 2 of them and this is where your two extra bytes are coming from. It should be
fwrite(&p,sizeof(PACKET),1,f);
The reason why the extra bytes only show up at the end of the file, is because you use fseek()
to position the file pointer, which is incremented correctly by 2. NB. When you are writing sequentially to a file, you don't need to use fseek()
anyway. Also, you have hard-coded with offsetCounter += 0x02;
instead of using offsetCounter += sizeof(PACKET)
.