Learn C - C File Example






Writing Data Into A File

We can write data into a file.

We can Create a file using fopen() function.

Then Write data into a file using fprintf() and fputs() functions.

Finally Close a file using fclose() function.

For testing, we create data into a file, my.c.


  #include <stdio.h> 
/*from   w w w  . ja va  2s . c  o  m*/
  int main(int argc, const char* argv[]) { 

      int i; 
      FILE *f; 

      f = fopen("my.c", "w+"); 

      for(i=0;i<5;i++){ 
          fprintf(f, "fprintf message %d\n",i); 
          fputs("fputs message\n", f); // no format 
      } 

      fclose(f); 
      printf("Data was written into a file\n"); 

      return 0; 
  } 

The code above generates the following result.





Reading Data From A File

We also can read data from a file using fgetc() function.


  #include <stdio.h> 
//from  w  ww  . ja va 2  s . c om
  int main(int argc, const char* argv[]) { 

      char ch; 
      FILE *f; 

      printf("Reading a file?.\n"); 
      f = fopen("demo.txt", "r"); 
      if(f==NULL){ 
          printf("Failed to read file\n"); 
          return 0; 
      } 

      while((ch = fgetc(f))  != EOF ) 
            printf("%c",ch); 

      fclose(f); 

      return 0; 
  } 

The code above generates the following result.