From: Tom Christiansen <tchrist@mox.perl.com>
Subject: TIP: How to open files
Date: 22 May 1998 13:58:00 GMT
Every confused about how to get files opened in different
ways? You can use open for a few, but sysopen for most
niceties. To use sysopen, first load
use Fcntl;
To open file for reading:
open(FH, "< $path") || die $!;
sysopen(FH, $path, O_RDONLY) || die $!;
To open file for writing, create new file if needed or else truncate old file:
open(FH, "> $path") || die $!;
sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT) || die $!;
sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666) || die $!;
To open file for writing, create new file, file must not exist:
sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT) || die $!;
sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666) || die $!;
To open file for appending, create if necessary:
open(FH, ">> $path") || die $!;
sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT) || die $!;
sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT, 0666) || die $!;
To open file for appending, file must exist:
sysopen(FH, $path, O_WRONLY|O_APPEND) || die $!;
To open file for update, file must exist:
open(FH, "+< $path") || die $!;
sysopen(FH, $path, O_RDWR) || die $!;
To open file for update, create file if necessary:
sysopen(FH, $path, O_RDWR|O_CREAT) || die $!;
sysopen(FH, $path, O_RDWR|O_CREAT, 0666) || die $!;
To open file for update, file must not exist:
sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT) || die $!;
sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0666) || die $!;
--tom
--
"I have many friends who question authority. For some reason most of 'em
limit themselves to rhetorical questions."
--Larry Wall