简体   繁体   English

读取文本文件的最后一行-C编程

[英]Read last line of a text file - C programming

I'm still a novice in C as I just started out. 刚开始我仍然是C语言的新手。 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); 在您的fscanf(tfptr, "%u:%u:%.2f\\n", &combo_trans, &ala_trans, &grand_total); , the %.2f will cause problem. %.2f会引起问题。

You can't specify the precision for floating-point numbers in scanf() unlike in the case of printf() . printf()不同,您不能在scanf()指定浮点数的精度。 See this answer. 看到这个答案。

So, instead of %.2f in the scanf format string, use just %f . 因此,不要在scanf格式字符串中使用%f代替%.2f

Since you just need the last line, you could just read the file line by line with fgets() and keep the last line. 由于只需要最后一行,因此可以使用fgets()逐行读取文件并保留最后一行。

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). 文件结束(或读取时发生错误)时, fgets()将返回NULL

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. 输入文件中的行被一一读取,并且当没有更多行要读取时, str (适当大小的字符数组)将具有最后读取的行。

You could then parse the string in str with sscanf() like 然后,您可以使用sscanf()解析str的字符串,例如

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()的返回值以查看文件是否真正打开。 fopen() will return NULL if some error occurred. 如果发生某些错误, fopen()将返回NULL

if( (tfptr = fopen("trans.txt", "r"))==NULL )
{
    perrror("Error");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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