
yapp
User
Oct 7, 2001, 9:00 AM
Post #2 of 2
(271 views)
|
|
Re: Add multiple lines to a file
[In reply to]
|
Can't Post
|
|
If your file has fixed-length records, you can simply seek() to that location and print the codes. In your case however, it's a bit difficult. You can't goto a line since a text file is nothing but dump binary data (ie: 0101 0101 1010 1010 1110). How would you edit the Nth line then, and insert some code? A computer can't. 2 Solutions: 1. get the file into an array; my @Array = <FILE>; then, edit the array and write it back. 2. open the file, read through until you reached the line preferred (write the read lines into a temp. file). then write the new lines to the temp. file, and write the last lines from the original to the end of the temp. file. Then copy the file over the original file. A bit difficult, but recommended for large files. Then again, if you're a great perl programmer, you know how to sysopen() the file with O_RDWR and then lock it. In this case you're file can't be overwritten, and the file copy will be less difficult (just seek() to the beginning, truncate() to 0 length. Then print the data from the other file into the original). This should be done like:
use Fcntl qw(:DEFAULT :flock); # Open original and temp sysopen(FILE, $File, O_RDWR) or die $!; flock(FILE, LOCK_EX); open(TEMP, "$File.tmp") or die $!; # Read through and test while(my $Line = <FILE>) { .... is this the nth line? -> go out of the loop print TEMP $Line; } # New data and remaining of <FILE> print TEMP $YourNewData; while(my $Line = <FILE>) { print TEMP $Line; } close(TEMP); # the re-open should be done better then this. # In fact, be eleminated # File copy open(TEMP, "$File.tmp") or die $!; seek(FILE, 0, 0) or die $!; truncate(FILE, 0) or die $!; print FILE <TEMP>; close(TEMP); # hehe close(FILE) Hope it helps, and this code is bug free. (have typed it directly into the browser)
|