How to print the content into the files using C language?

CServer Side ProgrammingProgramming

We can write a program in C for printing some content in to the file and print the following −

  • Number of characters entered into the file.
  • Reverse the characters entered into the file.

First, try to store number of characters into the file by opening the file in write mode.

For entering data into file, we use the logic as mentioned below −

while ((ch = getchar( ))!=EOF) {//after enter data press cntrl+Z to terminate
   fputc(ch, fp);

With the help of ftell, rewind, fseek functions, we can reverse the content that we already entered into the file.


Given below is a C program for printing some content into the file and print the number of characters and reverse the characters which are entered into the file −

 Live Demo

int main( ){
   FILE *fp;
   char ch;
   int n,i=0;
   fp = fopen ("reverse.txt", "w");
   printf ("enter text press ctrl+z of the end");
   while ((ch = getchar( ))!=EOF){
      fputc(ch, fp);
   n = ftell(fp);
   printf ( "No. of characters entered = %d\n", n);
   rewind (fp);
   n = ftell (fp);
   printf ("fp value after rewind = %d\n",n);
   fclose (fp);
   fp = fopen ("reverse.txt", "r");
   n = ftell(fp);
   printf ("reversed content is\n");
   fclose (fp);
   return 0;


When the above program is executed, it produces the following result −

enter text press ctrl+z of the end
No. of characters entered = 18
fp value after rewind = 0
reversed content is
Updated on 11-Mar-2021 07:51:00