LearnFrenzy
Sign in Take a free test

C Input / Output · Find the Error · Question 2

Error: reading from a file that failed to open Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("no-such-folder/marks.txt", "r");
    int ch = fgetc(fp);
    printf("%c\n", ch);
    fclose(fp);
    return 0;
}
  • A The mode should be "rb"
  • B fopen returns NULL because the file does not exist, and the program passes NULL to fgetc and fclose Correct
  • C fgetc returns char, not int
  • D There is no bug
Correct Answer: Option B

Always check: if (fp == NULL) { perror("marks.txt"); return 1; }. perror explains why, for example "No such file or directory".

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