Home  >  Article  >  Backend Development  >  file - php如何随机输出文件内一行?

file - php如何随机输出文件内一行?

WBOY
WBOYOriginal
2016-06-06 20:21:351392browse

我的文件很大,不想全部读取,再随机一行,想通过文件指针随机读取一行?

<code>1273517
12736
1273521
127
127358612735381273538fa
1273606
13
1273636
...</code>

回复内容:

我的文件很大,不想全部读取,再随机一行,想通过文件指针随机读取一行?

<code>1273517
12736
1273521
127
127358612735381273538fa
1273606
13
1273636
...</code>

现在有一个10G文件,要随机获取其中的一行数据。肯定不能一次把内容全部读取!!!
因此可以按字节随机读取
使用函数:
filesize 获取此文件的总字节
ftell 当前文件指针位置
fseek 定位文件指针位置
fgets 按行读取文件

实现思路有了吧:
开始位置可以随机取,即可实现随机读取数据。
比如总字节100,一行10字节,开始读取字节的位置随机取0~90字节中间的数。
为了数据的完整性,可以多读几行,那么结束位置就设为:开始位置+行数*每行字节大小
反正大概那个数就行了
因为每次读取不可能是一行的头,因为可以多读几行,然后用explode分割成一个数组,抛弃数组首尾,再随机获取其中的一条

下面这是按字节分页读取文件的内容,可以做个参考

<code>public static function readFileBySize($file, $currentPage=1, $pageSize=100000)
    {
        $read = "";
        $fileSize = filesize($file);
        $totalPage = ceil($fileSize/$pageSize);

        $start = filesize($file) - $currentPage*$pageSize;
        $stop  = filesize($file) - ($currentPage-1)*$pageSize;

        $fp = fopen($file, 'r');
        fseek($fp, $start, SEEK_SET);
        while(ftell($fp)  $fileSize,
            "pageSize" => $pageSize,
            "totalPage" => $totalPage,
            "currentPage" => $currentPage,
            "memory" => $memory,
            "data" => $read
        );
        return $returnData;
    }</code>

文件不大可以直接用file()函数读取一个文件,返回一个数组,数组的每一个元素对应文件的一行.

<code><?php header('Content-Type: text/plain; charset=utf-8');
$file = file(__FILE__, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$line = mt_rand(0, count($file)-1);
print_r($file);
echo $line.': '.$file[$line];</code></code>

文件大的话可以用文件指针.

<code><?php header('Content-Type: text/plain; charset=utf-8');
$file = __FILE__;
$fp = fopen($file, 'r');
$count = 0;
while ( !feof($fp) ) {
    $line = fgets($fp);
    echo $count.': '.$line;
    $count++;
}
fclose($fp);
echo "\n";
$rand = mt_rand(0, $count-1);
$fp = fopen($file, 'r');
$count = 0;
while ( !feof($fp) ) {
    $line = fgets($fp);
    if( $count === $rand ) {
        echo $rand.': '.$line;
        exit();
    }
    $count++;
}
fclose($fp);</code></code>

$file_path = 't.txt'; //文件路径
$s = exec('wc -l '.$file_path);//get lines
$i = 0;
$fp = fopen($file_path,'r');
while ( fgets($fp) !== false) {

<code>$i++;
if($i === 4){ // if lines = 4
    echo fgets($fp);
}</code>

}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn