fgets停止读取少字符(<)而不是行尾的行

时间:2018-09-22 19:14:29

标签: php fopen fgets

function getRandLineFromFile($fileName)
{
    $hendel = fopen($fileName, 'r+');
    if (!$hendel)
        return '';
    $cLineCount = 0;
    $sLineOut = '';
    while (!feof($hendel)) {
        $cLineCount++;
        $sLine = fgets($hendel);

        if (rand(1, $cLineCount) == $cLineCount) {
            $sLineOut = $sLine;
        }
    }
    return $sLineOut;
}

如果您尝试从字符较小的文件(<)中读取一行,则fgets会在该字符之前修剪字符串,而不是在该行末尾。

文件中的示例字符串:

wordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordword<twotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwo

结果:

wordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordword

0 个答案:

没有答案