Search code examples
cprintfstdinfopeneof

Relation of stdin and EOF in C


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


Solution

  • EOF is a macro that is very commonly equal to -1.

    1. Q1 :
      • 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 ).
      • In this sense the condition (i == EOF) returned true which is 1. which explains the answer.
    2. Q2 :
      • stderr is an output stream, meaning printing into it was a success
      • i = ..., i contains the number of characters written. >0
      • i == EOF evaluates to 0.
      • 0 got printed
    3. Q3 :
      • 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.
      • A write to that address resulted in a compilation or execution fails
    4. Q4 :
      • fprintf does its job and write 5 chars into the file f
      • i gets initialized with the value 5
      • i != EOF evaluates to 5 != -1, which is true, the is stored as the number 1 in memory
      • printed value is 1