perlfaq nodetype
faq_monk
<P>
Because you're using something like this, which truncates the file and
<EM>then</EM> gives you read-write access:
<P>
<PRE> open(FH, "+> /path/name"); # WRONG (almost always)
</PRE>
<P>
Whoops. You should instead use this, which will fail if the file doesn't
exist. Using ``>'' always clobbers or creates. Using ``<'' never
does either. The ``+'' doesn't change this.
<P>
Here are examples of many kinds of file opens. Those using
<CODE>sysopen()</CODE> all assume
<P>
<PRE> use Fcntl;
</PRE>
<P>
To open file for reading:
<P>
<PRE> open(FH, "< $path") || die $!;
sysopen(FH, $path, O_RDONLY) || die $!;
</PRE>
<P>
To open file for writing, create new file if needed or else truncate old
file:
<P>
<PRE> 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 $!;
</PRE>
<P>
To open file for writing, create new file, file must not exist:
<P>
<PRE> sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT) || die $!;
sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666) || die $!;
</PRE>
<P>
To open file for appending, create if necessary:
<P>
<PRE> 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 $!;
</PRE>
<P>
To open file for appending, file must exist:
<P>
<PRE> sysopen(FH, $path, O_WRONLY|O_APPEND) || die $!;
</PRE>
<P>
To open file for update, file must exist:
<P>
<PRE> open(FH, "+< $path") || die $!;
sysopen(FH, $path, O_RDWR) || die $!;
</PRE>
<P>
To open file for update, create file if necessary:
<P>
<PRE> sysopen(FH, $path, O_RDWR|O_CREAT) || die $!;
sysopen(FH, $path, O_RDWR|O_CREAT, 0666) || die $!;
</PRE>
<P>
To open file for update, file must not exist:
<P>
<PRE> sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT) || die $!;
sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0666) || die $!;
</PRE>
<P>
To open a file without blocking, creating if necessary:
<P>
<PRE> sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT)
or die "can't open /tmp/somefile: $!":
</PRE>
<P>
Be warned that neither creation nor deletion of files is guaranteed to be an atomic operation over
<FONT SIZE=-1>NFS.</FONT> That is, two processes might both successful create or unlink the same file! Therefore
<FONT SIZE=-1>O_EXCL</FONT> isn't so exclusive as you might wish.
<P>