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

前端 未结 12 2282
天命终不由人
天命终不由人 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:14

    The solutions here didn't work performantly for me. My solution grabs the last line (not the first line, in my case it was not relevant to get the first or last line) from the file and removes that from that file. This is very quickly even with very large files (>150000000 lines).

    function file_pop($file)
    {
        if ($fp = @fopen($file, "c+")) {
            if (!flock($fp, LOCK_EX)) {
                fclose($fp);
            }
            $pos = -1;
            $found = 0;
            while ($found < 2) {
                if (fseek($fp, $pos--, SEEK_END) < 0) { // can not seek to position
                    rewind($fp); // rewind to the beginnung of the file
                    break;
                };
                if (ord(fgetc($fp)) == 10) { // newline
                    $found++;
                }
            }
            $lastpos = ftell($fp); // get current position of file
            $lastline = fgets($fp); // get current line
    
            ftruncate($fp, $lastpos); // truncate file to last position
            flock($fp, LOCK_UN); // unlock
            fclose($fp); // close the file
    
            return trim($lastline);
        }
    }
    

提交回复
热议问题