Click here to Skip to main content
15,885,860 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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 !
Posted

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.
 
Share this answer
 
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:
C++
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
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!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900