fputc inserting extra bytes

This is a discussion on fputc inserting extra bytes within the C Programming forums, part of the General Programming Boards category; As part of a project I'm writing a small program to write 24-bit bitmap (BMP) files and am having a ...

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    2

    fputc inserting extra bytes

    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

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Did you open the file in binary mode?

  3. #3
    Registered User
    Join Date
    Sep 2009
    Posts
    2
    Well, I feel very stupid.

    Thanks much

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 01-11-2009, 11:52 PM
  2. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  3. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 11:36 AM
  4. From where these two extra bytes came?
    By Juganoo in forum C Programming
    Replies: 4
    Last Post: 12-24-2002, 05:32 PM
  5. socket question
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 07-19-2002, 02:54 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21