CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Guest

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





  2. #2
    Join Date
    Jul 1999
    Location
    India
    Posts
    51

    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
  •  





Click Here to Expand Forum to Full Width

Featured