Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Open file and print new line that is appended

Status
Not open for further replies.
Sep 10, 2013
4
0
0
US
Need to open a file and if a new line is appended, then need to print it.

Opening the file is no problem, but how does one check if a new line has been recently appended to the log file?
 
Hi

Just read, then wait, then start again :
Perl:
[b]open[/b] F,[green][i]"</input/file"[/i][/green];

[b]while[/b] (1) {
  [b]print[/b] $_ [b]while[/b] <F>;
  [b]sleep[/b] 1;
}

( Neither [tt]tail -f[/tt] has better solution : waits [tt]-s[/tt] ( [tt]--sleep-interval[/tt] ) seconds, then tries to read again. )


Feherke.
feherke.github.io
 
From CPAN, File::Tail seems to do what you want. It even recomputes the sleep time dynamically (up to a maximum limit) based on how active the log file is, so it doesn't continually poll the file when nothing much is happening.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
You can use the -M switch to test the file modification time:
Perl:
my $lasttime=0;
my $myinputfile="myinputfile.log";
while(1){
  if(-M $myinputfile<$lasttime){
    $lasttime=-M "myinputfile";
    open F,$myinputfile;
    print $_ while <F>;
    close F;
  }
  sleep 1;
}
It is not difficult to add the dynamically calculated sleep time.

: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Hi

Sorry Franco, but I am afraid that is not really practical :
man perlfunc said:
[tt]-M Script start time minus file modification time, in days.[/tt]
( man perlfunc | -X )

So better keep using the good old [tt]stat[/tt] function.

Regarding your code, reading the whole file after each modification not sounds too good. Also expecting a modification time less than the $lasttime sounds abit back to the future...

The OP not specified the used operating system, so hopefully this not applies, but as I know, on Windows the file time granularity is not really fine and not all changes will be detected promptly.


Feherke.
feherke.github.io
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top