2012-02-07 43 views
0

我是新来的文件处理,当我试图从键盘读取文件的数据并输出该文件的内容在屏幕上我没有得到所需的结果与下面的代码文件处理在c不产生所需的结果

/* 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; 

    } 

我得到的输出是这样的h?

还有一种方法,以便我可以找出在硬盘上创建该文件的位置?

+0

什么问题/错误? – m0skit0 2012-02-07 12:51:08

+1

虽然我们自己尝试并不困难,但如果您正在讨论意外/不想要的结果,通常会发布您期望的结果和取而代之的结果。 – Bart 2012-02-07 12:51:15

回答

1

首先,这是错误的,因为优先。

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

不是存储的字符,你会不断地保存字符和EOF之间的比较。所以你会连续储存一长串1

试试这个:

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

getcgetchar回报intSo ch should be int, not char。使用char可能意味着循环将永远不会在某些系统上终止。

+0

thanx ...它的工作... – haris 2012-02-07 12:56:53

+0

你能告诉我有没有办法让我可以找出硬盘上这个文件的创建地点? – haris 2012-02-07 13:05:42

+0

@haris在当前目录中。 – cnicutar 2012-02-07 13:06:14

0

行:

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

显然是错误的。似乎你想要:

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

取而代之。

+0

是的,你是赖特..但它的工作没有FP,以及我想知道如何? – haris 2012-02-07 13:01:03

+2

@haris:巧合。第二次调用fopen返回的指针与第一个返回的指针相同。如果您扩展该程序,或尝试在不同的编译器上运行该程序,则不太可能再发生这种情况。 – harald 2012-02-07 13:11:33

相关问题