Appending Data to a file - C File

C examples for File:File Operation

Description

Appending Data to a file

Demo Code

#include <stdio.h> 
void readData(void); 
int main()/*from   w  ww.  java2s .  co  m*/
{ 
   FILE *pWrite; 
   char name[10]; 
   char hobby[15]; 
  
   printf("\nCurrent file contents:\n"); 
  
   readData(); 
  
   printf("\nEnter a new name and hobby: "); 
  
   scanf("%s%s", name, hobby); 

   pWrite = fopen("hobbies.dat", "a"); 
   if ( pWrite == NULL ) 
      printf("\nFile cannot be opened\n"); 
   else { 
      fprintf(pWrite, "%s %s\n", name, hobby); 
      fclose(pWrite); 
      readData(); 
   }
}

void readData(void) { 
   FILE *pRead; 
   char name[10]; 
   char hobby[15]; 

   pRead = fopen("hobbies.dat", "r"); 
   if ( pRead == NULL ) 
      printf("\nFile cannot be opened\n"); 
   else { 
      printf("\nName\tHobby\n\n"); 
      fscanf(pRead, "%s%s", name, hobby); 

      while ( !feof(pRead) ) { 
         printf("%s\t%s\n", name, hobby); 
         fscanf(pRead, "%s%s", name, hobby); 
      }
   }
   fclose(pRead); 
}

Result


Related Tutorials