Click to See Complete Forum and Search --> : Read string from a file


July 3rd, 1999, 01:23 AM
Here is my source code.
I don't know why the last line is repeated.
Need help, thanks

#include <stdio.h>
#include <string.h>
int main(void) {
FILE *pfile;
char string[100];
if ((pfile=fopen("queduong.txt","w"))==NULL)
return 1;
while (1) {
printf("Input a string: ");
gets(string);
if (strcmp(string,"0")==0)
break;
fputs(string,pfile);
fputc('\n',pfile);
}
fclose(pfile);
if ((pfile=fopen("queduong.txt","r"))==NULL)
return 1;
while (!feof(pfile)) {
fgets(string,sizeof(string),pfile);
printf("\nThe string is: %s",string);
}
fclose(pfile);
return 0;
getchar();
}

Dhwanit
July 3rd, 1999, 01:31 AM
Ah! There is a slight subtlety in using the feof() and the fgets() functions. While feof() returns a nonzero on encountering EOF, fgets() returns a NULL. So just modify your code as follows:


while (!feof(pfile)) {
if( !fgets(string,sizeof(string),pfile) ) break;
printf("\nThe string is: %s",string);
}




It should work fine now!

Cheers!
DP