egeloen
egeloen

Reputation: 5864

How can I go to the nth line without using fgets() & file()?

I'm actually developping a class which allow me to open a file & read it line by line.

class File
{
    protected $path = null;

    protected $cursor = null;

    protected $lineCount = 0;

    public function isOpen()
    {
        return !is_null($this->cursor);
    }

    public function open($flag = 'r')
    {
        if(!$this->isOpen())
            $this->cursor = fopen($this->path, $flag);
    }

    public function getLine()
    {
        $this->open();

        $line = fgets($this->cursor);
        $this->lineCount++;

        return $line;
    }

    public function close()
    {
        if($this->isOpen())
            fclose($this->cursor);
    }
}

For some reason, I would like the file open at the line which is described by the lineCount property. I don't how can I update the open() method for doing that.

Instead of using the line count, I can use the size from the beginning of the file in octet and use the fseek method to move the cursor at the right place. But I don't know how can I get the size of a line in octet when I call the fgets method.

Thanks

Upvotes: 0

Views: 1064

Answers (1)

Marc B
Marc B

Reputation: 360762

Given that a text file can have any amount of text in a line, there's no 100% method to quickly jumping to a position. Unless the text format is exactly fixed and known, you'll have to read line-by-line until you reach the line number you want.

If the file doesn't change between sessions, you can store the 'pointer' in the file using ftell() (basically how far into the file you've read), and later jump to that position via fseek(). You could also have your getLine method store the offsets as it reads each line, so you build an array of lines/offsets as you go. This'd let you jump backwards in the file to any arbitrary position. It would not, however, let you jump 'forward' into unknown parts of the file.

Upvotes: 3

Related Questions