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.

Example

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

#include<stdio.h>
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");
   fseek(fp,0,SEEK_END);
   n = ftell(fp);
   printf ("reversed content is\n");
   while(i<n){
      i++;
      fseek(fp,-i,SEEK_END);
      printf("%c",fgetc(fp));
   }
   fclose (fp);
   return 0;
}

Output

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

enter text press ctrl+z of the end
TutorialsPoint
^Z
No. of characters entered = 18
fp value after rewind = 0
reversed content is
tnioPslairotuT
raja
Published on 09-Mar-2021 10:56:39
Advertisements