O'Reilly logo

C Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12

1: What's wrong with this program?
int main(void)
{
   int * fp;
   int k;

   fp = fopen("gelatin");
   for (k = 0; k < 30; k++)
       fputs(fp, "Nanette eats gelatin.");
   fclose("gelatin");
   return 0;
}
A1: It should have #include <stdio.h> for its file definitions. It should declare fp a file pointer: FILE *fp;. The function fopen() requires a mode: fopen("gelatin", "w"), or perhaps the "a" mode. The order of the arguments to fputs() should be reversed. For clarity, the output string should have a newline because fputs() doesn't add one automatically. The fclose() function requires a file pointer, not a filename: fclose(fp);. Here is a corrected version:
 #include <stdio.h> int main(void) { FILE * fp; int k; fp = fopen("gelatin", "w"); for (k = 0; k ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required