1

I know there might be many questions related to this one but I read most of them and still got no idea on how to do this.

Suppose I have a certain .txt file with each line being part of a chat log.

What I'd like to do is retrieve lines of the file, from line x onwards to the end. So if I have x = 450 I'd like to obtain the lines 450->eof(). I've tried this with stream_get_line and other functions but I always get stuck at "number of bytes to read" from file. How am I even suppose to know the number of bytes a line occupies, being them all different from each other?

Each line separates by \n and the files might have +500.000 lines.

Then I'd need to process each extracted line and I take it from here...

Here is a schema

if(file_exists($file)){
     $x = 500; //hard-coded
$file = fopen($file);
$single_line_or_could_be_all_at_once(exploded) = stream_get_line($file,$x,"\n"); //nope.
//process lines
}
4
  • 3
    You hit the nail on the head. You have to go line by line BECAUSE you don't know how much information is on one line. May 1, 2014 at 17:23
  • You want to use fgets. You can omit the length parameter. May 1, 2014 at 17:24
  • @thatidiotguy even if each line is separated by "\n" and it's assured there is no "\n" in the middle of the content?
    – 0LLiena
    May 1, 2014 at 17:26
  • @user3385828 Computers don't store things by "lines". That's a human construct.
    – Brad
    May 1, 2014 at 17:42

1 Answer 1

2

Since each line is of variable width, the only way to do this is to read from the beginning of the file, skipping over the first N lines that you don't need.

My PHP is very rusty, but it would go something like this (and feel free to edit the code to correct any syntax errors)

$lineNr = 1;
$in = fopen('file.txt', 'rb');
while($line = fread($in)) {
    if ($lineNr >= 450) { 
       // Use the line
    }
    $lineNr++;
}

If you want, you can modify the while to end when either the end of the file is reached, or a maximum line number desired is reached, like:

while($line = fread($in) && $lineNr < 550) {
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.