How to place a file pointer in the choosen line (e.g. 1 lime from the bottom) when opening file with fopen()?
-
1Check this question out http://stackoverflow.com/questions/4718305/reading-a-specific-line-from-a-text-file – dee-see Jan 18 '11 at 13:45
-
@domsterr - similar question, but not the same issue – ZombieDragon Jan 18 '11 at 14:01
4 Answers
If you know the offset within the file of the data you want you could always fseek () to it. Of course the problem is discovering where you need to fseek to within the file. If you can use SEEK_END as an option then the offset will be relative to the end of the file instead of the beginning, which may be helpful for you.
Alternatively, you could use the file () function to load the file data into an array. Each element on the array represents a line of the file, so the second to last element in the array will be the item you want.

- 31,179
- 15
- 87
- 129
You will probably have to read your file counting line endings "\n". Something like:
function fseek_line($handle, $count) {
while ((--$count > 0) && (fgets($handle, 4096) !== false)) { }
}
If you need the last line just open in append mode fopen("file.txt", "a");

- 316
- 2
- 5
Unfortunatly there is no easy way for this. Since files are not stored linewise there is no order to jump one line or several.
But check out this thread: fseek() by line, not bytes?