Appending of file not working. Any help?

Hi,

I’ve a file which is opened for writing and then i close it.
Again i open the same file for appending to its contents, but its not appending, its removing the older contents and freshly starting. Any help on whats the issue?

$tme=localtime();
my ($d,$m,$y) = (localtime)[3,4,5];
my $mdy1 = sprintf '%d-%d-%d', $d, $m+1, $y+1900;
print "\nDate is:$mdy1\n";
if ($mdy1 eq "0-3-2015") {$mdy1 = "28-2-2015";}
print "\nDate is:$mdy1\n";
$LOGFILE = "7252_Widevine_OemCrypto_Consolelog_User1";
$CONSOLE_LOGFILE = $LOGFILE.'_'.$mdy1.'.txt';

open CONSOLE_LOGF, ">", $CONSOLE_LOGFILE or die "Cannot open Console logfile $CONSOLE_LOGFILE:$!";
system("pwd");

# Doing some operations here.


close(CONSOLE_LOGF);

$tme=localtime();
($d,$m,$y) = (localtime)[3,4,5];
#my $mdy2 = sprintf '%d-%d-%d', $d-1, $m+1, $y+1900;
my $mdy2 = sprintf '%d-%d-%d', $d, $m+1, $y+1900;
print "\nDate is:$mdy2\n";
 
$LOGFILE1 = "7252_Widevine_OemCrypto_Consolelog_User1";
$CONSOLE_LOGFILE = $LOGFILE1.'_'.$mdy2.'.txt';

open(CONSOLE_LOGF, ">>", $CONSOLE_LOGFILE) || die "Cannot open Console logfile $CONSOLE_LOGFILE: $!";
# ........... Here is where the previous contents are erased and new file is created with new time(date is same here).....
system("pwd");

# Doing some operations here.

close(CONSOLE_LOGF);    

Hello ramki067,

I’m not sure what the problem is you are having your Perl is somewhat… rustic. I’ve cleaned it up with some best practices included. When I test this script, the output is first written, then appended, as expected.

Please go over it and look up the modules I used on http://www.metacpan.org . Happy hacking!

If you have any questions, please let me know.

#!/usr/bin/env perl

use v5.16;
use common::sense;
use autodie;

sub getTimestamp {
	my @ts = localtime();
	my $date = sprintf('%d-%d-%d', $ts[3], $ts[4]+1, $ts[5]+1900);	
	$date = "28-2-2015" if $date eq "0-3-2015";
	return $date;
}

my $date = getTimestamp();

say "\nThe date is: $date";

my $log_file_prefix = '7252_Widevine_OemCrypto_Consolelog_User1';
my $console_log_file = qq(${log_file_prefix}_${date}.txt);

# Open for reading
open(my $file_handle, '>', $console_log_file);

# Write something to the file
print $file_handle "foo\n";

# system() is fine, but please see http://stackoverflow.com/questions/799968/whats-the-difference-between-perls-backticks-system-and-exec
# also, I don't see the return value being assigned anywhere. If you want to capture that, use the qx// operator.
system('pwd');

# Doing some operations here. 

close($file_handle);

open(my $file_handle, '>>', $console_log_file);

# Append something to the file
print $file_handle "bar\n";

close $file_handle;

use Test::Simple tests => 1;

ok(qx{cat $console_log_file} eq "foo\nbar\n");
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.