开发者

total number of lines of a file (counting backwards)

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,开发者_JAVA技巧 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)


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, used fseek 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).


The opposite of EOF is pos == 0.

The POSIX tail command does this; for example code, see http://www.koders.com/c/fid8DEE98A42C35A1346FA89C328CC3BF94E25CF377.aspx


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜