
我们可以用 C 编写一个程序,用于将一些内容打印到文件中,并打印以下内容 -
首先,尝试通过以写入模式打开文件来将一定数量的字符存储到文件中。
用于输入将数据写入文件,我们使用如下逻辑 -
while ((ch = getchar( ))!=EOF) {//after enter data press cntrl+Z to terminate
fputc(ch, fp);
}借助ftell、rewind、fseek函数,我们可以反转已经输入到文件中的内容。
立即学习“C语言免费学习笔记(深入)”;
下面是一个用于打印的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中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号