0

I'm still a novice in C as I just started out. Here is a part of my function to open the file and then save the file lines into variables. I did while to loop until the end of file so I can get the last line, however it did not go as expected. So, I was wondering how can I get just the last line from a text file? Thank you.

    tfptr = fopen("trans.txt", "r");
    while (!feof(tfptr)){               
            fscanf(tfptr, "%u:%u:%.2f\n", &combo_trans, &ala_trans, &grand_total);                                              
    }
    fclose(tfptr);  

sample text file:

0:1:7.98
1:1:20.97
2:1:35.96
2:2:44.95
2:2:44.95
3:2:55.94
Michelle Ler
  • 55
  • 1
  • 7
  • 4
    Possible duplicate of [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Eugene Sh. Oct 27 '17 at 16:56

2 Answers2

0

What did go wrong? Did you get another line?

Don't use "&" as you don't want to save a pointer. That can be the reason of failure.

samthegolden
  • 1,366
  • 1
  • 10
  • 26
  • `scanf` requires pointers as arguments, omitting them is not an option (assuming those variables are not already pointers). – bta Oct 27 '17 at 17:02
0

In your fscanf(tfptr, "%u:%u:%.2f\n", &combo_trans, &ala_trans, &grand_total);, the %.2f will cause problem.

You can't specify the precision for floating-point numbers in scanf() unlike in the case of printf(). See this answer.

So, instead of %.2f in the scanf format string, use just %f.

Since you just need the last line, you could just read the file line by line with fgets() and keep the last line.

while( fgets(str, sizeof(str), tfptr)!=NULL );
printf("\nLast line: %s", str);

fgets() will return NULL when the file is over (or if some error occurred while reading).

The lines in the input file are read one by one and when there are no more lines to read, str (a character array of suitable size) will have the line that was read last.

You could then parse the string in str with sscanf() like

sscanf(str, "%u:%u:%f", &combo_trans, &ala_trans, &grand_total);

Also, you should be checking the return value of fopen() to see if the file was really opened. fopen() will return NULL if some error occurred.

if( (tfptr = fopen("trans.txt", "r"))==NULL )
{
    perrror("Error");
}
J...S
  • 5,079
  • 1
  • 20
  • 35
  • Corner cases: "`str` will have the line that was read last." fails in 2 cases: "if some error occurred while reading" (rare), the contents of `str` are indeterminate. If no lines were ever read, `str` may be uninitialized and so also indeterminate. – chux - Reinstate Monica Oct 27 '17 at 19:54