如何使用C语言将内容打印到文件中?
我们可以用C编写程序,将一些内容打印到文件中,然后打印以下内容-
输入文件的字符数。
反转输入文件中的字符。
首先,尝试通过在写入模式下打开文件将字符数存储到文件中。
为了将数据输入文件,我们使用以下逻辑:
while ((ch = getchar( ))!=EOF) {//输入数据后,按cntrl+Z终止
fputc(ch, fp);
}借助ftell,rewind和fseek函数,我们可以反转已经输入到文件中的内容。
示例
下面给出的是一个C程序,用于将一些内容打印到文件中,并打印字符数并反转输入到文件中的字符-
#includeint 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", n); rewind (fp); n = ftell (fp); printf ("fp value after rewind = %d\n",n); fclose (fp); fp = fopen ("reverse.txt", "r"); fseek(fp,0,SEEK_END); n = ftell(fp); printf ("reversed content is\n"); while(i 输出结果 执行以上程序后,将产生以下结果-
enter text press ctrl+z of the end nhooo ^Z No. of characters entered = 18 fp value after rewind = 0 reversed content is tnioPslairotuT
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下