Home > Backend Development > C++ > body text

How to print content to a file using C language?

WBOY
Release: 2023-09-13 15:01:02
forward
1455 people have browsed it

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 -

  • The characters entered into the file number.
  • Reverse characters entered into the file.

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);
}
Copy after login

With the help of ftell, rewind, and fseek functions, we can reverse the content that has been input into the file.

Example

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;
}
Copy after login

Output

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
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template