[PHP] Writing to file ... starting at the beginning.

Discussion in 'Web Design & Coding' started by vern, Jul 27, 2005.

  1. vern

    vern Dominus Political User Folding Team

    Messages:
    1,571
    Location:
    Minnesota, USA
    The following code appends to file successfully and works perfectly.

    Code:
    $handle = fopen("recent.txt", 'a'); 
    fwrite($handle, $add); 
    fclose($handle);
    
    However ... this code doesn't seem to write to the file. The only different is that I want this code to set the pointer at the beginning of the file instead of the end. Anybody have any clues to what is going on?

    Code:
    $handle = fopen("recent.txt", 'r+'); 
    fwrite($handle, $add); 
    fclose($handle);
    
    If you have code that does the same thing (writes a line at the beginning of a file), but is better and/or more efficient, please post.
     
  2. Khayman

    Khayman I'm sorry Hal... Political User Folding Team

    Messages:
    5,518
    Location:
    England
    use "w+" instead?
     
  3. Geffy

    Geffy Moderator Folding Team

    Messages:
    7,805
    Location:
    United Kingdom
    are you wanting to keep the contents of the file and just stick a line at the top?

    if you want to do that, you are going to need to read out the contents first and then append that to the end of the string you want at the top and then write the whole lot back again.

    PHP:
    <?php
    $file_contents 
    file_get_contents("recent.txt");
    $new_file $new_first_line "\n" $file_contents;
    $fp = @fopen("recent.txt""w");
    frwite($fp$new_file);
    fclose($fp);
    ?>
     
  4. vern

    vern Dominus Political User Folding Team

    Messages:
    1,571
    Location:
    Minnesota, USA
    @Geffy ... exactly what I was looking for! Much thanks!

    I didn't realize you had to create put the whole stream into a variable and then write that. Thanks.