如何使用 C 语言将内容打印到文件中?

cserver side programmingprogramming

我们可以用 C 语言编写一个程序,将一些内容打印到文件中,并打印以下内容 −

  • 输入到文件中的字符数。
  • 反转输入到文件中的字符。

首先,尝试以写入模式打开文件,将字符数存储到文件中。

为了将数据输入文件,我们使用如下逻辑 −

while ((ch = getchar( ))!=EOF) {//输入数据后按 cntrl+Z 终止
   fputc(ch, fp);
}

借助 ftell、rewind 和 fseek 函数,我们可以反转已输入文件的内容。

示例

下面是一个 C 程序,用于将一些内容打印到文件中,并打印字符数,并反转输入到文件中的字符。 −

#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);    rewind (fp);    n = ftell (fp);    printf ("fp value after rewind = %d
",n);    fclose (fp);    fp = fopen ("reverse.txt", "r");    fseek(fp,0,SEEK_END);    n = ftell(fp);    printf ("reversed content is
");    while(i<n){       i++;       fseek(fp,-i,SEEK_END);       printf("%c",fgetc(fp));    }    fclose (fp);    return 0; }

输出

当执行上述程序时,它会产生以下结果 −

enter text press ctrl+z of the end
TutorialsPoint
^Z
No. of characters entered = 18
fp value after rewind = 0
reversed content is
tnioPslairotuT

相关文章