|
-
July 3rd, 1999, 01:23 AM
#1
Read string from a file
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();
}
-
July 3rd, 1999, 01:31 AM
#2
Re: Read string from a file
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|