Jump to content


Photo

Writing new data to the top of a text file


  • Please log in to reply
4 replies to this topic

#1 jcbarr

jcbarr
  • Members
  • PipPipPip
  • Advanced Member
  • 219 posts

Posted 27 July 2006 - 01:34 AM

Here is the 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);
    }

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.

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 27 July 2006 - 01:42 AM

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

#3 jcbarr

jcbarr
  • Members
  • PipPipPip
  • Advanced Member
  • 219 posts

Posted 27 July 2006 - 04:34 AM

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.

#4 Ifa

Ifa
  • Members
  • PipPipPip
  • Advanced Member
  • 88 posts
  • LocationRauma, Finland

Posted 27 July 2006 - 05:10 AM

Can't he just use r+ in the fopen?
I'm just a guy who likes to code for fun...

#5 jcbarr

jcbarr
  • Members
  • PipPipPip
  • Advanced Member
  • 219 posts

Posted 27 July 2006 - 11:28 AM

No, it will overwrite what is already there. I tried that.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users