Writing character to file one by one - C File

C examples for File:Text File

Description

Writing character to file one by one

Demo Code

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

#define LENGTH 81                        // Maximum input length

int main(void) {

   char mystr[LENGTH];                    // Input string
   int mychar = 0;                        // Character for output
   FILE *pfile = NULL;                    // File pointer
   char *filename = "myfile.txt";

   printf("Enter an interesting string of up to %d characters:\n", LENGTH - 1);
   if (!fgets(mystr, LENGTH, stdin))       // Read in a string
   {//from  w  ww .  j av a  2 s  .  com
      printf("Input from keyboard failed.\n");
      exit(1);
   }

   pfile = fopen(filename, "w");

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

   for (int i = strnlen(mystr, LENGTH) - 1; i >= 0; --i)
      fputc(mystr[i], pfile);              // Write string to file backward

   fclose(pfile);                         // Close the file

                                          // Open the file for reading
   pfile = fopen(filename, "r");

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

                                          // Read a character from the file and display it
   printf("the data read from the file is:\n");
   while ((mychar = fgetc(pfile)) != EOF)
      putchar(mychar);                     // Output character from the file
   putchar('\n');                         // Write newline

   fclose(pfile);                         // Close the file
   pfile = NULL;
   remove(filename);                      // Delete the physical file
   return 0;
}

Result


Related Tutorials