Abhishek
Abhishek

Reputation: 33

fwrite in c going in an infinite loop

I am trying to update records in a .DAT file using fread and fwrite but somehow the loop runs infinitely. My code is:

FILE *fq;
Employee eme;
long int recsize_eme;
recsize_eme=sizeof(eme);

fq=fopen("EME.DAT","rb+");
if(fq==NULL)
{
    fq=fopen( "EME.DAT","wb+");
    if(fq==NULL)
    {
        printf("Can't Open File");
        exit(EXIT_FAILURE);
    }
}

rewind(fq);
while(fread(&eme,recsize_eme,1,fq)==1)
{
    if (compare_date(eme.pre_pay_date)==0 && compare_date(eme.pol_end_date)!=0)
    {
        int date[3];
        int n;
        n = sscanf(eme.pre_pay_date, "%d/%d/%d", &date[0], &date[1], &date[2]);
        if(date[1]!=12)
        {
            date[1]++;
        }
        else
        {
            date[1]=1;
            date[2]++;
        }

        snprintf(eme.pre_pay_date, sizeof(eme.pre_pay_date), "%d/%d/%d", date[0], date[1], date[2]);
        printf( eme.pre_pay_date );
        if (eme.pre_status!=0)
        {
            eme.pre_payment = eme.premium;
        }
        else
        {
            eme.pre_payment = eme.premium + eme.pre_payment;
        }
        printf( "%f %f\n",eme.premium,eme.pre_payment );
        fseek(fq,-recsize_eme,SEEK_CUR);
        fwrite(&eme,recsize_eme,sizeof(eme)/recsize_eme,fq);
    }
}
fclose(fp);

the function if updating the values correctly but when writing it keeps on printing the values infinitely. eme is an attribute of struct Employee which i have declared.

Upvotes: 0

Views: 1104

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

You are not saying on which platform you are, but I could reproduce your issue on MS-Windows with MingW gcc 4.6.2. The issue is that Windows does not flush the buffers after an fwrite(). Add

fflush(fq);

after the fwrite() call to solve this.

See also my SSCCE at https://github.com/afester/StackOverflow/tree/master/updateRecord

Upvotes: 1

Related Questions