Jump to content

Archived

This topic is now archived and is closed to further replies.

jcbarr

Writing new data to the top of a text file

Recommended Posts

Here is the code.

[code]    // Write players from team 1
    $handle = fopen("trades.txt", "a");
    $content = "$team1 send:\n";
    fwrite($handle, $content);
    if ($player1) {
        $sql = "SELECT * FROM batrating WHERE PID='$player1'";
        $query = mysql_query($sql);
        $a = mysql_fetch_array($query);
        $pos = $a['pos'];
        $fname = $a['firsname'];
        $lname = $a['lastname'];
        $content = "$pos $fname $lname\n";
        fwrite($handle, $content);
    } [/code]

I have opened the trades.txt and placed the cursor at the bottom and made it writeable. My question is this, is there any way for me to pen that text file and write the new data to the top of the text file without overwriting the data below it?

The script prints the players traded to the text file, and the way that it is right now it writes the newest trades at the bottom so you have to scroll down to see them. I want to be able to open the text file and see the newest trades at the top. Any help would be great.

Share this post


Link to post
Share on other sites
Use the file() function to read the file into an array.
Reverse the array.
Add the new line to the bottom of the array.
Reverse the array.
Write the new file.

Ken

Share this post


Link to post
Share on other sites
I don't know too much about arrays, but I'm reading up on it right now. array_reverse and all that stuff.

I just went the easy route, dumped the contents to a variable and then open the file, truncate it, write the new data, then dump the contents back in at the bottom.

Seems to be working, and the file shouldn't ever get that big to pose any problems.

Thanks for the help and pointing me in that direction.

Share this post


Link to post
Share on other sites
Can't he just use r+ in the fopen?

Share this post


Link to post
Share on other sites
No, it will overwrite what is already there. I tried that.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.