在c中从控制台中读取文件中的数据

时间:2013-11-11 17:18:17

标签: c

您好我有以下代码

#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <conio.h>

int main()
{
    FILE *fp;
    char c=' ';
    fp=fopen("E:\data.txt","w");
    if(fp==NULL)
    {
        printf("Cannot open file");
        exit(1);
    }
    printf("Write data & to stop press '.' :");
    while(c!='.')
    {
        c=getche();      
        fputc(c,fp);
    }
    fclose(fp);
    printf("\nContents Read:");
    fp=fopen("E:\data.txt","r");
    while(!feof(fp));
    printf("%c",getc(fp));
}

执行上面的代码时,我有以下输出

输出:

Write data & to stop press '.' :writing data into the file.

Contents Read:

输出不显示我输入的内容。

请帮助我哪里出错。

2 个答案:

答案 0 :(得分:4)

您的主要问题在于:

while(!feof(fp));

尾部分号是循环的完整主体,然后是对printf的单个调用。但是,Why is “while ( !feof (file) )” always wrong?还有其他原因。

答案 1 :(得分:1)

这里有拼写错误。

while(!feof(fp));将您带到文件末尾。

所以只需删除;