0

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.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
user2733944
  • 37
  • 1
  • 5

2 Answers2

4

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.

Community
  • 1
  • 1
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • I have removed the while(!feof(fp)); But when i given inputted text as "writingdata." I am getting "Contents read as w". Actually the contents read should be "writingdata." Pls help me. – user2733944 Nov 11 '13 at 17:28
  • Did you completely remove the loop and leave yourself with just a single call to `fgetc` as an argument to a single call to `printf`? If so, then the problem is pretty clear. You still need to loop, you just need to do it correctly. (just removing the semi-colon will help, but is not correct.) – William Pursell Nov 11 '13 at 17:31
1

There is typo here.

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

so just remove ;.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
  • I have removed the while(!feof(fp)); But when i given inputted text as "writingdata." I am getting "Contents read as w". Pls help me. Actually the contents read should be "writingdata." – user2733944 Nov 11 '13 at 17:25
  • remove only semi-colon, not the entire while loop. – Jeyaram Nov 11 '13 at 17:27
  • Extremelly sorry , i didnt noticed the semicolon, But i have gone into file location and opened the file ,when i look into the file , the inputted data is not displayed. – user2733944 Nov 11 '13 at 17:33