2

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?

Chaker
  • 1,197
  • 9
  • 22
  • 2
    What do you think `putchar(EOF)` does? – user253751 May 20 '15 at 22:42
  • I think it maybe should evaluate to `EOF` – Chaker May 20 '15 at 22:44
  • 1
    But *why* do you want to write `EOF` to the output? Anyway, `EOF` is not `unsigned char` so it won't work. – Weather Vane May 20 '15 at 22:44
  • @Chaker.benhamed Where does it say that `putchar` won't write anything if the argument is `EOF`? And why do you think that `putchar` will return `EOF` if there *wasn't* an error, when the documentation says it returns `EOF` on error? – user253751 May 20 '15 at 22:45
  • No i don't want to write `EOF` to the output but what i understand from `Linux Programmer's Manual` that `putchar` return `EOF` int the case of error. – Chaker May 20 '15 at 22:47
  • Yes but that is if `putchar()` fails, not the echo of what you write. Please just stick to your first method, which worked. – Weather Vane May 20 '15 at 22:48
  • But shouldn't `putchar` fails since `EOF` is not an ASCII value? – Chaker May 20 '15 at 22:49
  • 1
    Its failure is a property of the output stream, not what you send it. Sending `EOF` does *not* tell it to fail. – Weather Vane May 20 '15 at 22:51

1 Answers1

1

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.

autistic
  • 1
  • 3
  • 35
  • 80