php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #61523 First call to fgets in SplFileObject doesn't increase file pointer position
Submitted: 2012-03-27 07:54 UTC Modified: 2012-03-28 14:10 UTC
From: marc at lamarciana dot com Assigned:
Status: Not a bug Package: SPL related
PHP Version: 5.3.10 OS: Debian squeeze
Private report: No CVE-ID: None
 [2012-03-27 07:54 UTC] marc at lamarciana dot com
Description:
------------
Calling key() method in a new SplFileObject gives 0. This is the expected result.

If you call now fgets() method and again key() method it gives again 0 as a result. I think this is not the expected behavior.

Subsequent calls to fgets() followed by key() method increases the result by 1 (1, 2, 3...). This is again the expected result.

The behavior is the same with SplFileObject::READ_AHEAD flag.

More information:

http://stackoverflow.com/questions/9876999/first-call-to-fgets-in-splfileobject-doesnt-advance-file-key

Consider following text file, test.txt for the Test Script:
1
2
3

Test script:
---------------
<?php
$file = new SplFileObject('test.txt', 'r');
var_dump($file->key());
$line = $file->fgets();
var_dump($file->key());
$line = $file->fgets();
var_dump($file->key());
$line = $file->fgets();
var_dump($file->key());

Expected result:
----------------
int(0) int(1) int(2) int(3)

Actual result:
--------------
int(0) int(0) int(1) int(2)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-03-28 13:07 UTC] cataphract@php.net
This seems correct. The first line is line 0, not 1. The error is that you're calling key() before the first line is read. You should do it after (or just use a foreach loop).
 [2012-03-28 13:07 UTC] cataphract@php.net
-Status: Open +Status: Not a bug
 [2012-03-28 14:10 UTC] marc at lamarciana dot com
Ok, I see, thank you.

I think my confusion arose because fgets() reads next line from the file, but when no line has been read, fgets then reads current line, which is line 0. If when no line has been read we should consider we are somehow before line 0, then calling key() before reading any line maybe should return something different than 0, maybe -1 or false.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 11:01:28 2024 UTC