php-src
php-src copied to clipboard
Different results for seek() on SplFileObject and SplTempFileObject
Description
The following code:
<?php
declare(strict_types=1);
const LINES = 5;
const INDEX = 10;
$file_01 = new SplTempFileObject();
$file_02 = new SplFileObject('/tmp/test.txt', 'w+');
// write to files
for ($i = 0; $i < LINES; $i++) {
$file_01->fwrite("line {$i}" . PHP_EOL);
$file_02->fwrite("line {$i}" . PHP_EOL);
}
// reset
$file_01->rewind();
$file_02->rewind();
// seek
$file_01->seek(INDEX);
$file_02->seek(INDEX);
// show results
echo 'file_01: ' . $file_01->key(), PHP_EOL;
echo 'file_02: ' . $file_02->key(), PHP_EOL;
Resulted in this output:
file_01: 4
file_02: 5
But I expected this output instead:
file_01: 5
file_02: 5
PHP Version
PHP 8.1.6
Operating System
Windows 11
Appending to the test code above:
if($file_01->eof()) echo "Temp file at EOF", PHP_EOL;
if($file_02->eof()) echo "Real file at EOF", PHP_EOL;
try {
echo "[",$file_01->fgets(),"]", PHP_EOL;
} catch(RuntimeException) {
echo "Failed to read from temp file", PHP_EOL;
}
try {
echo "[",$file_02->fgets(),"]", PHP_EOL;
} catch(RuntimeException) {
echo "Failed to read from real file", PHP_EOL;
}
When INDEX is between 0 and 4 everything works as expected.
When INDEX is greater than 5 then everything works as expected (files are at EOF, reads fail), but the temp file's current line number is down as reported.
When INDEX is equal to 5, both files are on line 5, but the temp file is at EOF and fails to read, while the real file reckons there is still more to go, reading and outputting an empty string (the one following the final PHP_EOL in the file).
...But the temp file does have the same contents as the real file.