3

There is php code:

#!/usr/bin/php
<?php
if ($file = fopen("file.txt", "r")) {
        while(!feof($file)) {
                $line = fgets($file);
                echo "----" , $line , "----";
            }
        fclose($file);
}
?>

and empty file "file.txt"

[root@localhost]# ls -l  file.txt 
-rw-r--r-- 1 root root 0 Апр 21 10:14 file.txt
[root@localhost]# file file.txt 
file.txt: empty

Why i get ? feof should be true in first loop or am i wrong?

[root@localhost ]# php -f  test2.php
--------

[root@localhost ]# 
harp1814
  • 1,494
  • 3
  • 13
  • 31
  • 3
    There is a huge writeup https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong and https://www.php.net/manual/en/function.feof.php#67261 from the manul. – Nigel Ren Apr 21 '20 at 07:37
  • 2
    To clarify: if you haven't read anything from the file through `fgets`, the end of the file hasn't been reached yet – Nico Haase Apr 21 '20 at 07:44

1 Answers1

5

Yes, that is because the file is already empty but PHP doesn't know it until it executes the fgets() method.

In order to avoid PHP reads the first empty line, you have to check that fgets is not false. To achieve that should do something like:

if ($file = fopen("file.txt", "r")) {
    while (($line = fgets($file)) !== false) {
        echo "----" , $line , "----";
    }
    fclose($file);
}
JesusValera
  • 629
  • 6
  • 14