r/C_Programming • u/snchart • Aug 09 '26
how to read last N lines of file/input
I have a file foo.txt for example, and i need to read last 5 for example strings of it in C, how i can do that? I didn't found any tutorial for that + stack overflow is currenly read-only
9
Upvotes
15
u/mikeblas Aug 09 '26
What have you tried so far?
56
u/ComplexPeace43 Aug 09 '26
Seek to the end of the file and work backwards.
5
u/sciencekm Aug 09 '26
Almost every C student goes through this problem from K&R 2nd Edition. Look up the source code for numerous "tail" implementations.
Exercise 5-13. Write the program tail, which prints the last n lines of its input. By default, n is set to 10, let us say, but it can be changed by an optional argument so that
tail -n
prints the last n lines. The program should behave rationally no matter how unreasonable the
input or the value of n. Write the program so it makes the best use of available storage; lines should be stored as in the sorting program of Section 5.6, not in a two-dimensional array of fixed size.
8
u/mlt- Aug 09 '26
Map it to memory and start filling a ring buffer of N char * pointers. Or as ComplexPeace43 said, go backwards.
4
u/lisnter Aug 10 '26
Or just iuse tail directly: tail -5 foo.txt | yourprogram
Then you can just read from stdin
6
u/WoodyTheWorker Aug 09 '26
Simplest solution: read the file line by line, and only save the last five lines.
2
u/Specific-Housing905 Aug 09 '26
Linux has an app called tail that will do it. Have a look at the source code of the GNU core-uils on github
2
u/start_select Aug 09 '26 edited Aug 09 '26
Either build a new string/blob of bytes as you go, or record the number of bytes processed until you hit your target N.
Then either use that new string or slice a new one using the length you calculated.
I’m not going to write you code, figure out how to implement the algorithm.
——
If it’s a stream you need to use “buffers” aka “windows”.
Keep an array of the last 5 lines read. Everytime you hit another new line, add an entry to the front of the array and pop one off the end. So you always have a window of the last 5 lines read.
2
u/Total-Box-5169 Aug 09 '26
The fastest way is to memory map the file and count N '\n' characters starting at the end. The last N lines are right after the Nth '\n' character found when going backwards. If you reached the start instead the Nth '\n' character then there are less than N lines.
3
u/Wertbon1789 Aug 09 '26
The easiest, possibly dumbest, thing I could think of is reading the entire file into memory (or memory mapping it, if it's big), and using memrchr to find the last n newlines, saving the offset of all of them, and replacing the newlines with null-terminators to get actual strings. If it's a pipe, so non-seekable, you could allocate buffers for n lines, and store the lines to them, and interate through them, until the end of the input, and then printing the lines you got stored, from the oldest to the newest... Idk, I would look into what the
tailcommand does, maybe from busybox so one can actually read the source.1
u/SafeSpirit673 Aug 09 '26
If you mean like enter separeted lines, you can read "\n" characters
1
u/flumphit Aug 09 '26
Sounds like you want to read the source code to tail(1).
1
u/SmokeMuch7356 Aug 09 '26
To make this a single-pass operation, read lines into a circular queue:
When you're done
linesstores the last 5 lines read from the file, andhwill be the index of the least-recently-read line (i.e, the head of the queue). To print those lines out you'd use something likeTo minimize unnecessary reads, use
fseekto set the file position some number of bytes before the end, based on how long you expect the lines to be. For example, if you know your input lines won't be longer than 80 characters, then offset something like 440 characters before the end of the file, then find the beginning of the next line:then do the
getlinedance above.1
u/redoo715 Aug 09 '26
I am still learning C, so I decided to treat your question as an exercise.
Basically, what I did is I moved to the end of the file, then I went backwards checking every character if it they match the new line character. If '\n' is reached 5 times for example, I memorize the position and display the last 5 lines. (I tested it on linux)
Link to the c file
1
u/ReallyEvilRob Aug 10 '26
Use
fseek(fp, 0, SEEK_END)to move to the very end of the file. Get the size of the file withsize_t position = ftell(fp);. Then use a loop to iterate backwards usingpositionandfseek(fp, position, SEEK_SET);. With each loop iteration, read a character withfgetc(fp)and check for a newline character. When you've counted 5 newlines (or if you hit the beginning of the file before counting 5 newlines), thenpositionwill have the correct file offset for where you need to start printing from.To use this method, your file needs to be open in binary mode with "rb". If you're on Windows, text files end with '\r' and '\n', unlike POSIX systems which are only '\n'. Because of that you should scan for a CRLF sequence, i.e.
memcmp(buffer, "\r\n", 2) == 0.1
u/eruciform Aug 10 '26
Read thru to find the line start positions as you go, maintaining the last N in a list, then when done, seek to that position and read again
Or seek to the end and read a character at a time backwards until you hit the N+1th line end, then back up and go from there
Either way
Theres no way to seek to Nth line because files arent indexed by lines, only by bytes
1
u/ern0plus4 Aug 11 '26
The difficulty is that - in case of file - there's no such as readline() but backwards. You have to figure out some trick: e.g. assume that one line is 80 long, so you should seek -5 * 80 from EOF. If it contains 5 lines, you're okay, but if not... read another bunch of lines, and you still can't be sure if it it contains the missing number if lines.
It's a good example that a first sight simple problem is sometimes not so simple.
1
u/JGhostThing Aug 09 '26
Use the "last" command on Linux. Seriously.
0
u/Maqi-X Aug 09 '26
maybe first count how many lines the file has and then on the second pass skip
total lines - Nand read the rest