skip to Main Content

Why does fgets and fopen fail to "open a stream" except for the last line of an input file?

I’m trying to read a file of directory trees and txt files and open each file.

filelist.txt contains:

a/1600/file.txt
b/1600/file.txt
c/1600/file.txt

Directory:

enter image description here

c/1600/file.txt contains the text directory c

The output in index.php is this:

Warning: file_get_contents(a/1600/file.txt ): Failed to open stream:
No such file or directory in /Users/joe/Sites/php/index.php on line 9

Warning: file_get_contents(b/1600/file.txt ): Failed to open stream:
No such file or directory in /Users/joe/Sites/php/index.php on line 9

directory c

Why is the contents of only c/1600/file.txt output?

index.php (PHP 8.2):

$handle = fopen("filelist.txt", "r");


if ($handle) {
    
    while (($line = fgets($handle)) !== false) {

        $eachfilecontents = file_get_contents($line, true);

        echo $eachfilecontents;

    }

    fclose($handle);
}

2

Answers


  1. I have modify your code to check file before proceed to next

    <?php
    $handle = fopen("filelist.txt", "r");
    if($handle){
        while(($line = fgets($handle)) !== false) {
            $line = trim($line);    
            if(file_exists($line)){ 
                $eachfilecontents = file_get_contents($line);
                echo $eachfilecontents;
            }
            else{ echo "File not found: " . $line . "<br>"; }
        }    
        fclose($handle);
    }    
    ?>
    

    replace your index.php file code with this and it will return you data from all of files.

    Login or Signup to reply.
  2. The relevant part of the error message is No such file or directory. From fgets() documentation:

    Reading ends when length – 1 bytes have been read, or a newline (which is included in the return value)

    If last line works, it’s because the file doesn’t have a trailing new line.

    You can e.g. trim it yourself:

    $eachfilecontents = file_get_contents(rtrim($line), true);
    

    On a side note, I’m not sure why you’re using the file_get_contents() function with the use_include_path flag, it sounds like an unnecessary burden.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search