Home >Backend Development >C++ >How to print content to a file using C language?
We can write a program in C that prints some content to a file and prints the following -
First, try to store a certain number of characters into the file by opening the file in write mode.
For inputting data into a file, we use the following logic -
while ((ch = getchar( ))!=EOF) {//after enter data press cntrl+Z to terminate fputc(ch, fp); }
With the help of ftell, rewind, and fseek functions, we can reverse the content that has been input into the file.
The following is a C program for printing to write some content to a file and print the number of characters and reverse the characters entered into the file -
Live Demonstration
#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</p><p>", n); rewind (fp); n = ftell (fp); printf ("fp value after rewind = %d</p><p>",n); fclose (fp); fp = fopen ("reverse.txt", "r"); fseek(fp,0,SEEK_END); n = ftell(fp); printf ("reversed content is</p><p>"); while(i<n){ i++; fseek(fp,-i,SEEK_END); printf("%c",fgetc(fp)); } fclose (fp); return 0; }
When the above program is executed, the following results are produced-
enter text press ctrl+z of the end TutorialsPoint ^Z No. of characters entered = 18 fp value after rewind = 0 reversed content is tnioPslairotuT
The above is the detailed content of How to print content to a file using C language?. For more information, please follow other related articles on the PHP Chinese website!