如何使用 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
", 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP