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

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

    I came up with this idea yesterday:

    function read_and_delete_first_line($filename) {
      $file = file($filename);
      $output = $file[0];
      unset($file[0]);
      file_put_contents($filename, $file);
      return $output;
    }
    
    0 讨论(0)
  • 2020-12-03 03:59

    There is no more efficient way to do this other than rewriting the file.

    0 讨论(0)
  • 2020-12-03 04:02

    My problem was large files. I just needed to edit, or remove the first line. This was a solution I used. Didn't require to load the complete file in a variable. Currently echos, but you could always save the contents.

    $fh = fopen($local_file, 'rb');
    echo "add\tfirst\tline\n";  // add your new first line.
    fgets($fh); // moves the file pointer to the next line.
    echo stream_get_contents($fh); // flushes the remaining file.
    fclose($fh);
    
    0 讨论(0)
  • 2020-12-03 04:03

    Here's one way:

    $contents = file($file, FILE_IGNORE_NEW_LINES);
    $first_line = array_shift($contents);
    file_put_contents($file, implode("\r\n", $contents));
    

    There's countless other ways to do that also, but all the methods would involve separating the first line somehow and saving the rest. You cannot avoid rewriting the whole file. An alternative take:

    list($first_line, $contents) = explode("\r\n", file_get_contents($file), 2);
    file_put_contents($file, implode("\r\n", $contents));
    
    0 讨论(0)
  • 2020-12-03 04:07

    You could store positional info into the file itself. For example, the first 8 bytes of the file could store an integer. This integer is the byte offset of the first real line in the file.

    So, you never delete lines anymore. Instead, deleting a line means altering the start position. fseek() to it and then read lines as normal.

    The file will grow big eventually. You could periodically clean up the orphaned lines to reduce the file size.

    But seriously, just use a database and don't do stuff like this.

    0 讨论(0)
  • 2020-12-03 04:08

    I wouldn't usually recommend opening up a shell for this sort of thing, but if you're doing this infrequently on really large files, there's probably something to be said for:

    $lines = `wc -l myfile` - 1;
    `tail -n $lines myfile > newfile`;
    

    It's simple, and it doesn't involve reading the whole file into memory.

    I wouldn't recommend this for small files, or extremely frequent use though. The overhead's too high.

    0 讨论(0)
提交回复
热议问题