Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP feof($file) returns false on the empty file

Tags:

php

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 ]# 
like image 693
harp1814 Avatar asked Dec 08 '25 17:12

harp1814


1 Answers

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);
}
like image 88
JesusValera Avatar answered Dec 11 '25 05:12

JesusValera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!