首页  >  文章  >  后端开发  >  如何使用C语言将内容打印到文件中?

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

WBOY
WBOY转载
2023-09-13 15:01:021393浏览

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

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

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

首先,尝试通过以写入模式打开文件来将一定数量的字符存储到文件中。

用于输入将数据写入文件,我们使用如下逻辑 -

while ((ch = getchar( ))!=EOF) {//after enter data press cntrl+Z to terminate
   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</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;
}

输出

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

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

以上是如何使用C语言将内容打印到文件中?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除