为什么除了文件最后一行之外,fgets 和 fopen 无法“打开流”?

问题描述 投票:0回答:1

为什么

fgets
fopen
无法“打开流”(除了输入文件的最后一行)?

我正在尝试读取目录树和txt文件的文件并打开每个文件。

filelist.txt
包含:

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

目录:

enter image description here

c/1600/file.txt 包含文本

directory c

index.php 中的输出是这样的:

警告:file_get_contents(a/1600/file.txt):无法打开流: 第 9 行 /Users/joe/Sites/php/index.php 中没有此类文件或目录

警告:file_get_contents(b/1600/file.txt):无法打开流: 第 9 行 /Users/joe/Sites/php/index.php 中没有此类文件或目录

目录c

为什么只输出c/1600/file.txt的内容?

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);
}
php fopen php-8.2
1个回答
0
投票

我已修改您的代码以检查文件,然后再继续下一步

<?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);
}    
?>

用此替换您的 index.php 文件代码,它将返回所有文件中的数据。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.