3

How to place a file pointer in the choosen line (e.g. 1 lime from the bottom) when opening file with fopen()?

Rik Heywood
  • 13,816
  • 9
  • 61
  • 81
ZombieDragon
  • 131
  • 1
  • 2
  • 12

4 Answers4

4

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.

GordonM
  • 31,179
  • 15
  • 87
  • 129
1

There is a SplFileObject::seek method that can position the pointer to Nth line.

Boy
  • 1,182
  • 2
  • 11
  • 28
1

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");

Tralamazza
  • 316
  • 2
  • 5
0

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?

Community
  • 1
  • 1
Mathias
  • 2,484
  • 1
  • 19
  • 17