CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
write to file existing file

 



orult
Novice

Sep 27, 2005, 4:44 AM

Post #1 of 4 (539 views)
write to file existing file Can't Post

Hi !!!

I want to open file, read some data, change values and than store it back to file.

I am trying to open file for writing like this:

open (CONTROLFILE,">$requestControlFile") || die("can't open $requestControlFile -> $!");

but problem is that with this command always new file is created and my old file is than overwriten.

any advice.



thanks,


KevinR
Veteran


Sep 27, 2005, 9:30 AM

Post #2 of 4 (538 views)
Re: [orult] write to file existing file [In reply to] Can't Post

what many people do is read the file into an array, loop through the array and make changes, then overwrite the file with the modified array.


Code
open (CF,"$requestControlFile") || die("can't open $requestControlFile -> $!");  
my @data = <CF>;
close(CF);
for (@data) {
#do something
}
open (CF,">$requestControlFile") || die("can't open $requestControlFile -> $!");
for (@data) {
print CF $_;
}
close(CF);


you can also use Tie::File to do the same thing, but the above should do what you want.
-------------------------------------------------


orult
Novice

Sep 28, 2005, 1:57 AM

Post #3 of 4 (535 views)
Re: [orult] write to file existing file [In reply to] Can't Post

thanks Kevin,

I have already done something like that, but I was thinking that maybe I missed some command

anyway thank you.


davorg
Thaumaturge / Moderator

Sep 28, 2005, 9:00 AM

Post #4 of 4 (533 views)
Re: [orult] write to file existing file [In reply to] Can't Post

Did you read the documentation for 'open'? Sounds like you want the '+<' mode. And don't forget to flock the file.


Code
use Fcntl ':flock'; 

open (CONTROLFILE,"+<$requestControlFile")
|| die("can't open $requestControlFile -> $!");

flock CONTROLFILE, LOCK_EX;

my @file = <CONTROLFILE>;
# do something to the data in @file
# then when you want to write it back...

seek CONTROLFILE, 0, 0;
truncate CONTROLFILE, 0;
print CONTROLFILE @file;
close CONTROLFILE;


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives