如何逐行读取大文件?

本文翻译自:How to read a large file line by line?

I want to read a file line by line, but without completely loading it in memory. 我想逐行读取文件,但没有将其完全加载到内存中。

My file is too large to open in memory, and if try to do so I always get out of memory errors. 我的文件太大,无法在内存中打开,如果尝试这样做,我总是会走出内存错误。

The file size is 1 GB. 文件大小为1 GB。


#1楼

参考:https://stackoom.com/question/ta2n/如何逐行读取大文件


#2楼

You can use the fgets() function to read the file line by line: 您可以使用fgets()函数逐行读取文件:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
    }

    fclose($handle);
} else {
    // error opening the file.
} 

#3楼

if ($file = fopen("file.txt", "r")) {
    while(!feof($file)) {
        $line = fgets($file);
        # do same stuff with the $line
    }
    fclose($file);
}

#4楼

Use buffering techniques to read the file. 使用缓冲技术读取文件。

$filename = "test.txt";
$source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
while (!feof($source_file)) {
    $buffer = fread($source_file, 4096);  // use a buffer of 4KB
    $buffer = str_replace($old,$new,$buffer);
    ///
}

#5楼

小心'while(!feof ... fgets()'东西,fgets可能会出错(返回false)并永远循环,而不会到达文件末尾。codaddict最接近正确,但是当您的“ while fgets”时循环结束,检查feof;如果不正确,则错误。


#6楼

Function to Read with array return 读取数组返回的函数

function read_file($filename = ''){
    $buffer = array();
    $source_file = fopen( $filename, "r" ) or die("Couldn't open $filename");
    while (!feof($source_file)) {
        $buffer[] = fread($source_file, 4096);  // use a buffer of 4KB
    }
    return $buffer;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值