2

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

                }
            }

        }
  • 3
    [`fscanf`](http://man7.org/linux/man-pages/man3/scanf.3.html) returns a value that indicates how many items were assigned. ***ALWAYS CHECK IT!*** There must be some example code that thinks it's okay to not check this return value. Beginners are apparently finding it because this happens several times every day. We must find this resource and destroy it! – Jonathon Reinhart Dec 31 '14 at 07:50

1 Answers1

4

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
    }
Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36