A C quiz had these four questions that deal with fprintf and EOF. They weren't really explained in the section of the course related to these questions and I can't find good answers for them online.
Is the reason for the numbers printed on the screen and/or compilation fail the result of fprintf or its relation to EOF?
#include <stdio.h> int main(void) { int i; i = fprintf(stdin,"Hello!"); printf("%d",i == EOF); return 0; }
Answer: the program outputs 1
#include <stdio.h> int main(void) { int i; i = fprintf(stderr,"Hello!"); printf("%d",i == EOF); return 0; }
Answer: the program outputs 0 to the stdout stream
#include <stdio.h> int main(void) { FILE *f; int i = fprintf(f,"Hello!"); printf("%d",i == EOF); return 0; }
Answer: the compilation or execution fails
#include <stdio.h> int main(void) { FILE *f = fopen("file","w"); int i = fprintf(f,"Hello!"); printf("%d",i != EOF); return 0; }
Answer: the program outputs 1
EOF is a macro that is very commonly equal to -1.
stdin
is an input stream. Therefore using fprintf on it created a conflict, which apparently was handled by fprintf()
and returned -1. ( as mentioned in the comments the return values in case of an error can be any negative number ).(i == EOF)
returned true which is 1. which explains the answer.stderr
is an output stream, meaning printing into it was a successi = ...
, i
contains the number of characters written. >0i == EOF
evaluates to 0.fprintf
tries to print into a stream with the address f
f
is a pointer with a garbage value, which means it might be pointing to a memory owned by the OS.fprintf
does its job and write 5 chars into the file f
i
gets initialized with the value 5i != EOF
evaluates to 5 != -1
, which is true, the is stored as the number 1 in memory