【问题标题】:PHP: Using fgets() and fscanf() to read them into variablesPHP:使用 fgets() 和 fscanf() 将它们读入变量
【发布时间】:2023-03-24 23:50:02
【问题描述】:

我是 PHP 新手,我很难理解为什么我的代码不起作用。任何人都可以看到这是为什么? 对于我的代码,我正在尝试使用fgets()fscanf() 的组合来读取文本文件,并且我想将它们放入一组变量中。我还想在文件到达 EOF 时返回 false,并且我希望它在文本编辑器中将这些记录读入变量并回显它们的输出。

    $fp = fopen ("branches.txt", "r");
    while ($branch = fgets ($fp)) {
        $branch=trim($branch);
        if (filesize('branches.txt') == 0){
           echo "The file is DEFINITELY empty";
        }
        printf("%2d: ");
        if ($branch === FALSE) print ("FALSE\n");
        else print ($branch . "</br>");
    }
    while ($info = fscanf($fp, "%i %lf %lf")) {
       list ($properties, $income, $expenditure) = $info;
       echo $info;
    }
    fclose ($fp);

文本编辑器:位置/字符串 整数浮点浮点数

i.e isver heat 12 160.0 77.0

【问题讨论】:

    标签: php while-loop file-handling fgets


    【解决方案1】:

    这里

    printf("%2d:");

    缺少 int 值。

    您已经将文件 (while ($branch = fgets ($fp))) 读入 EOF。现在您需要在使用while ($info = fscanf($fp, "%i %lf %lf")) 读取文件之前重置指针。

    rewind($fp);
    while ($info = fscanf($fp, "%i %lf %lf")) {
    .....
    

    查看此链接了解更多信息: http://php.net/manual/en/function.rewind.php

    【讨论】:

    • 打印中究竟缺少什么整数值?
    • printf("%2d: "); %2d 的变量在哪里。它应该是 printf("%2d: ", some_variable);1 。不是吗?
    • 我昨天已经尝试过了,但它不会改变输出
    猜你喜欢
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    相关资源
    最近更新 更多