简体   繁体   中英

Read last line of a text file - C programming

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM