Is this the most efficient way to get and remove first line in file?

前端 未结 12 2281
天命终不由人
天命终不由人 2020-12-03 03:53

I have a script which, each time is called, gets the first line of a file. Each line is known to be exactly of the same length (32 alphanumeric chars) and terminates with \"

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 04:18

    This will shift the first line of a file, you dont need to load the entire file in memory like you do using the 'file' function. Maybe for small files is a bit more slow than with 'file' (maybe but i bet is not) but is able to manage largest files without problems.

    $firstline = false;
    if($handle = fopen($logFile,'c+')){
        if(!flock($handle,LOCK_EX)){fclose($handle);}
        $offset = 0;
        $len = filesize($logFile);
        while(($line = fgets($handle,4096)) !== false){
            if(!$firstline){$firstline = $line;$offset = strlen($firstline);continue;}
            $pos = ftell($handle);
            fseek($handle,$pos-strlen($line)-$offset);
            fputs($handle,$line);
            fseek($handle,$pos);
        }
        fflush($handle);
        ftruncate($handle,($len-$offset));
        flock($handle,LOCK_UN);
        fclose($handle);
    }
    

提交回复
热议问题