简体   繁体   中英

Reading data from file in console in c

Hi i have the following code

#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));
}

And when executing the above code , i have the following output

Output:

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

Contents Read:

Output doesn't display the contents which i have inputted.

Please help me where did i went wrong.

Your primary issue is here:

while(!feof(fp));

The trailing semi-colon is the complete body of the loop, followed by a single call to printf. However, Why is “while ( !feof (file) )” always wrong? for other reasons.

There is typo here.

while(!feof(fp)); take you to end of file.

so just remove ; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM