SiteBanner

Storing data in data files is central and critical to all forms of computing.  'C' offers a robust collection of file-handling functions.  Let's build both file-read and file-write programs.

 

(right-click to download)

/* pgm14-a source WRITING to file */

#include <stdio.h>

#define TESTFILE "./secret"

int main(void) {
     char *line1 = "It's TRUE! I had a date with Queen Elizabeth\n";
     char *line2 = "She was a great conversationalist and quite funny.\n";
     int retcode;
     FILE *fileptr;            // this data type is central to many file/stream functions

     fileptr = fopen(TESTFILE, "w"); // "w" flags to Write to file
     if (fileptr == NULL) {
          perror("fopen() to write ");
          return(-1);
          }

     // fputs() does NOT write out the string terminating NULL
     retcode = fputs(line1, fileptr);
     if (retcode == EOF) {
          perror("fputs()");
          fclose(fileptr); // we need to close what we opened
          return(-1);
          }

     retcode = fputs(line2, fileptr);
     if (retcode == EOF) {
          perror("fputs()");
          fclose(fileptr); // we need to close what we opened
          return(-1);
          }

     fclose(fileptr); // we need to close what we opened
     printf("\n");

     return(0);
     }

 

(right-click to download)

/* pgm14-b source     READING from file */

#include <stdio.h>

#define TESTFILE "./secret"
#define STRINGLEN 128          // more than enough string storage for our examples

int main(void) {
     char buf[STRINGLEN];
     FILE *fileptr; // this data type is central to many file/stream functions

     fileptr = fopen(TESTFILE, "r"); // "r" flags to Read from file
     if (fileptr == NULL) {
         perror("fopen() to read ");
         return(-1);
         }

     printf("\n");

     // fgets() ADDS the string-terminating NULL automatically
     while (fgets(buf, STRINGLEN - 1, fileptr) != NULL) 
          printf("%s", buf);

     fclose(fileptr); // we need to close what we opened
     printf("\n");

     return(0);
     }

 

  • Typically program arguments are used ("main(int argc, char *argv[])") INSTEAD of hard-coded filename
  • It's good practice to REPORT when 'fopen()' has a problem (file missing, file permissions unexpected)
  • It's a wise practice to include a 'fflush(fileptr)' call, which makes sure any pending output is written
  • More error-checking is recommended at each write-to-file or read-from-file operation