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 ...

Get C Primer Plus, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.