0

I tried this code:

int main(void)
{
   FILE *fp;    // Assuming fp is initialized
   putw(11,fp);  /* Instead of writing 11 to the file this statement
                    wrote an unwanted character into the file */

   /* However when I put 11 in single quotes as,
   putw('11', fp);
   It worked properly and wrote integer 11 into the file */
}

What is the explanation for this behaviour?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    You didn't really try this. That program crashes due to an uninitialized `fp`. – Jens Jun 18 '16 at 12:32
  • Your `putw('11',fp);` can only have "worked properly" if your `int` is 16 bits. My 32-bit `int` created a file size 4 containing `31 31 00 00` – Weather Vane Jun 18 '16 at 13:01

2 Answers2

3

putw() writes a "word" which is a binary int into the FILE. It does not format the int, it just writes it. Same as fwrite() with sizeof(int).

You might consider fprintf() instead:

fprintf(fp, "%d", 11);

With your old code, the file will contain four bytes like 00 00 00 0B or 0B 00 00 00 depending on the endian mode of your system. Or maybe eight bytes if you have a 64-bit int platform. With the new code it will write two bytes always: 31 31 (that's two hex ASCII codes for '1').

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
2

putw('11',fp); isn't a valid character constant, it worked only by coincident. Also if you compile the source with gcc with proper flags, it will warn you about it:

warning: multi-character character constant [-Wmultichar]

If you want to write the integer with text format, use fprintf:

fprintf(fp, "%d", 11);

If you want to write the integer in binary format, use fwrite or putw in the right way:

int n = 11;
fwrite(&n, sizeof n, 1, fp);

or

putw(n, fp);
fluter
  • 13,238
  • 8
  • 62
  • 100
  • `'11'` does not work "by coincident" although I only became aware of it through these pages. `int i = '1234';` initialises a value `0x31323334` but I can't quote a source, sorry. You received a warning, not an error. – Weather Vane Jun 18 '16 at 13:30
  • @WeatherVane It is not conforming C, the result of `int i = '1234';` is implementation defined, so it is not portable and different compliers might give you different result. That's why the warning. – fluter Jun 18 '16 at 13:32
  • Thanks, it is [covered here](http://stackoverflow.com/questions/6944730/multiple-characters-in-a-character-constant) but implementation-defined rather than undefined. – Weather Vane Jun 18 '16 at 13:39