LearnFrenzy
Sign in Take a free test

C Input / Output · Predict the Output · Question 11

Counting characters with while (!feof(fp)) – output Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>

int main(void) {
    FILE *fp = tmpfile();
    if (fp == NULL)
        return 1;
    fputs("abc", fp);
    rewind(fp);
    int count = 0;
    while (!feof(fp)) {
        fgetc(fp);
        count++;
    }
    printf("%d\n", count);
    fclose(fp);
    return 0;
}
  • A 4 Correct
  • B 3
  • C 0
  • D The loop never ends
Correct Answer: Option A

After reading 'c', feof is still false – the end is detected only by the next, failing fgetc, which is counted too. Loop on fgetc(fp) != EOF to get 3.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links