Search code examples
cfgetcputchar

Merging fgetc and putchar in while loop


I am writing a simple code to print the content of the file to stdout.

When i use this :

while((c=fgetc(fp))!=EOF)putchar(c);

It works like it should but i wanna to merge putchar and fgetc. So i wrote

while(putchar(fgetc(fp))!=EOF);

But it doesn't seem to work. So i check the return value of putchar

RETURN VALUE
       fputc(),  putc()  and  putchar()  return  the  character  written as an
       unsigned char cast to an int or EOF on error.

So why it doesn't work?


Solution

  • getchar returns one of the following:

    • A character, represented as an unsigned char value (e.g. typically between 0 and 255, inclusive of those values), converted to an int. Thus, there are typically one of 256 (UCHAR_MAX+1, technically) values that fall into this category.
    • A non-character, EOF, which has a negative value, typically -1.

    Thus, getchar may typically return one of 257 (not 256) values. If you attempt to convert that value straight to char or unsigned char (e.g. by calling putchar), you'll be losing the EOF information.

    For this reason you need to store the return value of getchar into an int before you convert it to an unsigned char or char.