在C文件处理不产生所需的结果 [英] File Handling in c not producing the required result

查看:85
本文介绍了在C文件处理不产生所需的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的文件处理,当我试图从键盘到文件和输出读取数据文件的内容在屏幕上,我没有得到期望的结果与code以下

  / *您可以通过keyboared到文件末尾数据,并将其写入
文件名为​​输入agian阅读屏幕*从这个文件中的数据/#包括LT&;&stdio.h中GT;   诠释的main()
   {
     FILE * FP;
     焦炭℃;
     的printf(从keyboared \\ n输入数据);     FP =的fopen(input.txt中,W);     而((C =的getchar()!= EOF))
     {
       putc将(C,FP);
     }     FCLOSE(FP);     的printf(从文件读取指定输入\\ n中的数据);     FOPEN(input.txt的,R);     而((C = GETC(FP))!= EOF)
     {
       的printf(%C,C);
     }     FCLOSE(FP);     返回0;  }

我得到的输出是这样的H +

另外有没有办法让我可以找出在硬盘中创建这个文件在哪里?


解决方案

一起来,这是因为precedence错了。


 ,而((C =的getchar()!= EOF))
                       ^


而不是存储的字符,你会不断地保存字符之间的比较 EOF 。所以,你会不断地存储长线 1

试试这个:

 ,而((C =的getchar())!= EOF)
                  ^

GETC 的getchar 收益 INT 所以 CH INT ,不是字符 。使用字符可能意味着循环将永远不会在某些系统上终止。

I am new to file handling, when I tried to read data from keypad to file and output the contents of that file on the screen I am not getting the desired result with the code below

/* get data from the keyboared till the end of file and write it to the 
file named "input" agian read the data from this file on to the screen*/

#include <stdio.h>

   int main()
   { 
     FILE *fp;
     char c;
     printf("enter the data from the keyboared\n");

     fp=fopen("input.txt","w");

     while((c=getchar()!=EOF))
     {
       putc(c,fp);
     }

     fclose(fp);

     printf("reading the data from the file named input\n");

     fopen("input.txt","r");

     while((c=getc(fp))!=EOF)
     {
       printf("%c",c);
     }

     fclose(fp);

     return 0;

  }

I am getting output something like this h ?

Also is there a way so that i can find out where on the harddisk this file is created?

解决方案

First up, this is wrong because of precedence.

while((c=getchar()!=EOF))
                       ^

Instead of storing the character, you will continuously store the comparison between the character and EOF. So you will continuously store a long line of 1.

Try this:

while((c=getchar())!=EOF)
                  ^

Second getc and getchar return int. So ch should be int, not char. Using a char could mean the loop will never terminate on some systems.

这篇关于在C文件处理不产生所需的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆