Thursday 20 December 2018

c - last line of file is duplicated using fscanf





I am trying to print what is inside my history.txt file.



It works fine. The problem is the last part, it prints the last line twice.



example output:




abcd1234 12/31/2014 03:28:20 PM 5.00 0.00 // this will be printed twice
abcd1234 12/31/2014 03:28:20 PM 5.00 0.00 // here


here is the part where I used for reading and printing the file.



  while(!feof(fp))
{
fscanf(fp,"%s %s %s %s %f %f",code,hodate,hitime,distime,&deb1,&cre1);

if(strcmp(code,x.accnum)==0)
{
if(strcmp(hodate,currentdate)==0)
{
printf("%s\t%s\t%.2f\t%.2f\n",hodate,hitime,deb1,cre1);

}
}

}


Answer



Using feof() like this is wrong.



while (fscanf(hist, "%s %s %s %s %f %f", acR, hdate, htime, dis, &deb, &cre) == 6)
{
// Put your code here
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...