As part of a project I'm writing a small program to write 24-bit bitmap (BMP) files and am having a quite confusing problem. The file header includes the size of the file with the least significant byte first, and the next 3 bytes in order of increasing significance - so if the size was 0xAFCB6, for example, that would be in the header as "B6 FC 0A 00."
To construct the header I made a char array with an entry for every byte of the header, pretty straightforward. My code to write the bytes of the filesize in the correct order looks like:
Code:
char header[] = { ... filesize&0xFF,(filesize>>8)&0xFF,(filesize>>16)&0xFF,(filesize>>24)&0xFF, ... }
Which should (and usually does) work.
To write the header to the file I wrote the following:
Code:
void fputchars(const char *str, FILE *out, int len) {
int i;
for(i = 0; i < len; i++) {
fputc(str[i], out);
}
}
Which also should (and generally does) work.
However, with certain filesizes, an extra byte shows up in the file - not the incorrect byte, a complete extra one that shifts everything over and just generally messes everything up. The filesize I mentioned above is one such number - 0xAFCB6 results in "B6 FC 0D 0A 00" to be written to the file - so in the end I have more bytes written to the file than there are in the header array, fputc seems to be sneaking them in.
I believe the problem occurs when the least significant byte of the filesize is >= 128, which leads me to believe it has something to do with the chars in question being signed or unsigned, but I can't figure out why additional bytes are being written.
Any thoughts? Am I misusing fputc?
Thanks