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

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

    No need to create a second temporary file, nor put the whole file in memory:

    if ($handle = fopen("file", "c+")) {             // open the file in reading and editing mode
        if (flock($handle, LOCK_EX)) {               // lock the file, so no one can read or edit this file 
            while (($line = fgets($handle, 4096)) !== FALSE) { 
                if (!isset($write_position)) {        // move the line to previous position, except the first line
                    $write_position = 0;
                } else {
                    $read_position = ftell($handle); // get actual line
                    fseek($handle, $write_position); // move to previous position
                    fputs($handle, $line);           // put actual line in previous position
                    fseek($handle, $read_position);  // return to actual position
                    $write_position += strlen($line);    // set write position to the next loop
                }
            }
            fflush($handle);                         // write any pending change to file
            ftruncate($handle, $write_position);     // drop the repeated last line
            flock($handle, LOCK_UN);                 // unlock the file
        }
        fclose($handle);
    }
    

提交回复
热议问题