Reading and Writing Strings to a Text File - C File

C examples for File:Text File

Description

Reading and Writing Strings to a Text File

Demo Code

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define LENGTH 81                           // Maximum input length
int main(void)
{
   char *proverbs[] = { "test.\n", "test.\n","test.\n" };
   char more[LENGTH];                        // Stores a new proverb
   FILE *pfile = NULL;                       // File pointer
   char *filename = "myfile.txt";

   pfile = fopen(filename, "w");

   if (pfile ==NULL) {
      printf("Error opening %s for writing. Program terminated.\n", filename);
      exit(1);/*from w  w w .  ja va  2 s  . co m*/
   }
   setvbuf(pfile, NULL, _IOFBF, BUFSIZ);     // Buffer file output

   for (size_t i = 0; i < sizeof proverbs / sizeof proverbs[0]; ++i) {
      if (EOF == fputs(proverbs[i], pfile)) {
         printf("Error writing file.\n");
         exit(1);
      }
   }
   fclose(pfile);                            // Close the file
   pfile = NULL;

   pfile = fopen(filename, "a");

   if (pfile == NULL) {
      printf("Error opening %s for appending. Program terminated.\n", filename);
      exit(1);
   }
   setvbuf(pfile, NULL, _IOFBF, BUFSIZ);     // Buffer file output

   printf("Enter proverbs of up to %d characters or press Enter to end:\n", LENGTH - 1);
   while (true) {
      fgets(more, LENGTH, stdin);             // Read a proverb
      if (more[0] == '\n')                     // If its empty line
         break;                                // end input operation
      if (EOF == fputs(more, pfile))             // Write the new proverb
      {
         printf("Error writing file.\n");
         exit(1);
      }
   }
   fclose(pfile);                              // Close the file
   pfile = NULL;

   pfile = fopen(filename, "r");

   if (pfile == NULL)          // Open the file to read it
   {
      printf("Error opening %s for reading. Program terminated.\n", filename);
      exit(1);
   }
   setvbuf(pfile, NULL, _IOFBF, BUFSIZ);       // Buffer file input

                                               // Read and output the file contents
   printf("The proverbs in the file are:\n");
   while (fgets(more, LENGTH, pfile))           // Read a proverb
      printf("%s", more);                      // and display it

   fclose(pfile);
   remove(filename);
   pfile = NULL;
   return 0;
}

Result


Related Tutorials