in reply to File Read

A file mode of "+>" will clobber the contents (if any) of the file you open that way (see perlopentut), which would explain why it's always empty.

Replies are listed 'Best First'.
Re^2: File Read
by rheaton (Acolyte) on Mar 12, 2007 at 13:31 UTC

    I understand that this will Truncate the file but should it be truncating it when it is opened? I want it to truncate on write of data. Is there something different that I need to do to make that work? I inadvertantly left out of the code supplied previously that in the else I printf file_name "1"; to lock the file if it wasnt locked. So another Process cannot access it while This one is using it. I am essentially serializing a Parallel Process with these locks because it has to be due to database and workfile access.

      My question becomes... How can I Open a file once, read the contents of the file then Truncate these contents to another value and then close the file?

        You'd probably use sysopen with seek and truncate, but that's probably still not what you really want to do. Read the entries in perlfaq5 on file locking and flock if you want to do this correctly.

        Here's an example.

        use POSIX qw( LOCK_EX SEEK_SET ); # Open a shared file for reading and writing open my $fh, '<+', $filename or die "Can't open $filename for reading: $!"; flock $fh, LOCK_EX | LOCK_NB or die "Can't get an exclusive lock on $filename: $!"; # Read one line. my $contents = <$fh>; # Empty the file. seek $fh, 0, SEEK_SET or die "Can't seek to the start of $filename: $!"; truncate $fh, 0 or die "Can't truncate $filename: $!"; # Put something new in there. print $fh "...." or die "Can't write to $filename: $!"; close $fh or die "Can't write to $filename: $!";

        ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊