如何查看文件的最后一行? [英] How do I view the last line of the file ?

查看:408
本文介绍了如何查看文件的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从linux实现tail命令,而且我不知道如何显示文件的最后N行和最后n个字节。

有人能帮帮我吗?

谢谢!

I try to implement tail command from linux, and I do>not know how to display the last N lines of the file and the last n bytes.
Can anybody help me?
Thanks !

推荐答案

从头开始读取保存最新的'N'直到你到达文件末尾的行。或者你可以从最后开始阅读并搜索行尾字符以识别每行开始的位置。
Read from the beginning saving the latest 'N' lines until you get to the end of file. Or you could start at the end reading backwards and searching for end of line characters to identify where each line starts.


要添加理查德所说的,C没有行在一个文件中 - 它只知道一个换行符字符(根据运行代码的系统而变化)表示当从一个文件或控制台读取一行时新行从这里开始 。

这使得找到最后一行有问题,因为要做到这一点,你需要最后一行的开头,这是由文件中的最后一个换行符表示的。

阅读从文件中获取的字节数通常非常简单:获取文件的大小 - 具体取决于您编译的系统,但请尝试:

To add to what Richard says, C doesn't have a concept of "lines" in a file - it just knows that a "newline" character (which varies depending on the system the code is running on) indicates a "new line starts here" when it is told to read a line from a file or the console.
That makes finding the last line problematic, because to do that you need the start of the last line, which is indicated by the last newline in the file.
Reading a number of bytes from the file is normally pretty simple: get the size of the file - exactly how will depend on the system you compile for, but try:
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

然后你可以使用fseek移动到大小,减去你想要的字节数,然后读到最后。

您可以使用它来查找大文件中的最后一行:选择一个大于文件中最长行的块大小,从末尾读取多个字节并向后搜索新行指示符。

对于一个小文件,请按理查德的说法读取每一行。

但是没有简单的方法可以做到这一点!

You can then use fseek to move to the size, minus the number of bytes you want, and read to the end.
You can use that to find the last line in a big file: pick a "block size" that is larger than the longest line in the file can be, read that many bytes from the end and search backwards in that for a newline indicator.
For a small file, read each line as Richard says.
But there is no simple way to do it!


这篇关于如何查看文件的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆