function that adds lines to the top of the file

Discussion in 'PHP' started by t7584, Mar 12, 2006.

  1. #1
    function that adds lines to the top of the file

    this function adds 1 line to the bottom of the file
    $gbfile='gb.txt';

    function add($str){
    global $gbfile;
    $tmp = trim($str);
    $fp=fopen($gbfile,'a+');
    flock($fp, LOCK_EX);
    fwrite($fp, $tmp. "\n");
    flock($fp, LOCK_UN);
    fclose($fp);
    }
    I want to write a function (exactly like above), but that adds lines to the top of the file. If simply replace a+ with r+ in
    $fp=fopen($gbfile,'a+') it won't be the same because of "\n" in fwrite($fp, $tmp. "\n"); . Can somebody write such function? What is . (point) in fwrite($fp, $tmp. "\n"); ?
     
    t7584, Mar 12, 2006 IP
  2. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #2
    The only way I have been able to accomplish this is the read the file into memory, prepend the lines of text, and replace the file with the new contents. This is the same approach you would use if you are editing text within the file -- read, change in memory, overwrite the file.

    I should add that there are not many times when you want to do this. It will result in lots of extra disc writing activity and, as the file grows in size, it will slow your machine. The file needs to be rarely used. If it is a log, for instance, you should always append lines to the end of the file. If you want to display the contents of the file in reverse order, do an in memory reverse sort of the lines.

    If it is an html file, you are better separating the header from the content of the file so that you can change the look and feel opf your website without needing to change all the pages.
     
    clancey, Mar 12, 2006 IP