Forum Moderators: coopster & phranque

Message Too Old, No Replies

Adding to TOP of a page

how to add to the top of a page

         

Mr Anonymous

12:44 am on Aug 25, 2003 (gmt 0)

10+ Year Member



ok, i have a little dilemma. i have made this news/reviews script, and i want it to write to the top of a file, but also keep the files original contents below it.

for example
#say this is my news file

blah

#and i just posted to it, i want it to do this

new post
blah

how do i do this? please tell me if i need to include a little more info

amoore

1:11 am on Aug 25, 2003 (gmt 0)

10+ Year Member



Open the file for reading. Open another, new file for writing. Read in any part of the old file that you want above your new post. Write it to the new file. Write the new stuff to the new file. Read the rest of the old file and write it to the new file. Close both files. Rename the new file to have the name of the old file.

Something like this seems pretty close:

open (OLD, $oldfile) or die "Cant open $oldfile: $!"
open (NEW, ">", $oldfile . "~") or die "Cant open new file: $!"
while (<OLD>) {
print NEW;
if ( /#new stuff goes after this comment/ ) {
print NEW, $newstuff;
}
}
close OLD;
close NEW;
rename $oldfile . "~", $oldfile or die "Cant rename file: $!";

kenta

11:20 am on Aug 26, 2003 (gmt 0)

10+ Year Member



I assume you'll have something to display the file. I know this isn't the exact answer but.... why not reverse it? Write to the file normally and make your program to display the contents in reversed order. Read each entry and throw them in an array, then reverse the contents of the array then output the information.

Mr Anonymous

1:01 am on Aug 31, 2003 (gmt 0)

10+ Year Member



Thanks for all the help, but I seemed to have figured it out myself :). I just did this:

open(FIRSTRUN,"$myfile");
@vn=<FIRSTRUN>;
close (FIRSTRUN);
####
$message= "$mymessage";
$message=~ s/\n/<br>/g;
####
open(OVERWRITE,"$myfile");
print OVERWRITE qq~$message @vn~;
close (OVERWRITE);

Thanks for the quick responses!
:)

IanKelley

9:29 am on Sep 1, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You've got the right idea (definitely don't add the extra overhead of using two files) but what happens if another instance of the script opens and writes to your file while the first instance is in between read and write? The data from one of the file writes is going to get lost completely.

Instead:
Open the file (without clobbering it)
lock it
read it
seek back to beginning
write new data
write what you read above
close file (will automatically unlock).

But I should also mention that the reversing idea from above would be faster as long as the file isn't going to be getting too big.