文件的总行数(向后计数)
对于给定的文件,我可以向后计算行数吗?即从EOF开始,计算行数直到开始?
我可以 fseek 到文件末尾。从那里开始,继续寻找新行字符(新行的指示)并继续增加我的 line_number 计数。但我的结束条件应该是什么呢?
EOF有相反的吗? :)
我自己的建议:如果我正在寻找从末尾开始的第 X 行,我总是可以从这个行号开始得到它:total_lines - X --- 足够公平吗?
动机:我有兴趣从一个巨大(读起来非常大)文件的末尾到达第 X 行。所以,寻找最优解。
PS:这不是作业(尽管我是终身学生:p)
For a given file, can I count number of lines backwards? i.e. starting from EOF, counting the lines till the beginning?
I could fseek to the end of the file. Start form there, keep looking for new line char (indication of a new line) and keep incrementing my line_number count. But what should be my ending condition?
Is there any opposite of EOF? :)
My own suggestion: If I am looking for Xth line from end, I could always get it from beginning at this line number : total_lines - X --- fair enough?
Motive: I am interested in getting to Xth line form the end of a HUGE (read really huge) file. So, looking for the most optimal solution.
PS: This is not a homework (though I am a lifetime student :p)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我完成此操作时(例如,编写了标准
tail
的粗略等效项),我从末尾读取了一个块,计算了其中的行数(如果我没有足够的行数),使用 fseek 向后读取另一个块(但我不确定后者是否真的发生过,除非我在测试中强制执行)。When I've done this (e.g., wrote a rough equivalent of the standard
tail
) I've read a block from the end, counted the lines in it, if I didn't have enough lines, usedfseek
to go backwards and read another block (but I'm not sure the latter has ever really happened except when I forced it to in testing).EOF 的相反是 pos == 0。POSIX
tail 命令执行此操作;有关示例代码,请参阅 http://www.koders.com/c/fid8DEE98A42C35A1346FA89C328CC3BF94E25CF377.aspx
The opposite of EOF is pos == 0.
The POSIX tail command does this; for example code, see http://www.koders.com/c/fid8DEE98A42C35A1346FA89C328CC3BF94E25CF377.aspx
如果您想向后打印行,可以使用递归来执行此操作(不确定计数是什么意思,因为向前计算行数与向后计算行数相同)。这听起来像是 C 入门的家庭作业,所以我不会写代码,而是这样想。读取一行,如果不是 EOF 则递归读取下一行,否则打印该行并返回。
If you want to print lines backwards you can use recursion to do this (not sure what you mean by count because counting the number of lines is the same forwards as it is backwards). This sounds like a homework problem for intro to C so I will refrain from putting code but think of it this way. Read a line, if it's not EOF recursively read the next line otherwise print the line and return.