0
    #define F_PWD_FSCANF  "%05d%30[^\n]%15s%25s%30s\n"
    #define F_PWD_FPRINTF "%05d%-30s%-15s%-25s%-30s\n"    
    
int main(){
    FILE *fp=fopen(FILENAME(F_PWD),"a+");  

            if (!fp)               
            {
                perror("ERROR:");
                FreeMalloc(pw,pw_t);
                exit(EXIT_FAILURE);
            }

    while(!feof(fp))
                {
                    count++;
                    fscanf(fp,F_PWD_FSCANF,&pw_t->id,pw_t->name,pw_t->userID,pw_t->pwd,pw_t->emailID);
    
                    if ((strcmp(pw->userID, pw_t->userID)==0) || (strcmp(pw->emailID, pw_t->emailID)==0))
                    {
                        printf("\n[%s]-[%s] ",pw->userID,pw_t->userID);
                        printf("\n[%s]-[%s] ",pw->emailID,pw_t->emailID);
                        COLOR(RED);
                        ToastMsg(TOAST_MSG_USER_EMAIL_EXISTS, row_x, col_y,1500);
                        COLOR(YEL);
                        ToastMsg( TOAST_MSG_OPTION, row_x, col_y,0);
                        retVal=1;
                        while_loop=false;
                        break;
                    }
                     printf("\neof loop");
                }
return 0;
}

File created with fprintf()

00001Anil Dhar anil1960 -N[VY&# anil.dhar@live.com
00002Rita Dhar anil1960 -_VaN&# rita.dhar@gmail.com
00003Shailja Dhar shailja1960 -`UNVYWN&# shailja.dhar@me.com
00004Tony P Singh tony1234 -a[f ! tony@x.com

However, I am unable to read this file using fscanf() because it doesn't satisfy the eof condition. As a result, it goes into an endless loop.

The fprintf() and fscanf() format specifiers are defined as pre-processor dietcrivers.

What is wrong with the code?

Anil
  • 15
  • 4
  • 1
    Does this answer your question? [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Jeff Mercado Nov 15 '21 at 02:42
  • 1
    Always check the return value of `fscanf`. That's just basic defensive programming and will also help with debugging. If `fscanf` even fails once your loop will be infinete as it will continue to fail. Equally bad, using the results of `fscanf` without checking the return value could result in accessing uninitalised data. – kaylum Nov 15 '21 at 02:43
  • @kaylum- Agreed. Done. However, the file was corrupted. Issue resolved. – Anil Nov 15 '21 at 03:22
  • Don't use feof as a loop condition. Use the return of fscanf to decide when the loop is finished. https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Jerry Jeremiah Nov 15 '21 at 05:04

0 Answers0