LearnFrenzy
Sign in Take a free test

C Input / Output · Find the Error · Question 4

Error: FILE fp = fopen(...) Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 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("data.txt", "w");
    fprintf(&fp, "hello\n");
    fclose(&fp);
    return 0;
}
  • A "w" must be "wt"
  • B fopen returns a FILE *, which cannot initialise a FILE object; fp must be declared FILE *fp Correct
  • C fprintf needs a format specifier
  • D There is no bug
Correct Answer: Option B

Programs only ever work with pointers to FILE objects that the library creates. Declare FILE *fp = fopen(…);, check it for NULL, and pass fp itself.

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