1. Perl
  2. builtin functions
  3. here

sysopen function - specify open mode in detail

You can specify the open mode in detail using the sysopen function. open function open mode You can use it when you want to do more than that.

sysopen(my $fh, $file, O_WRONLY | O_EXCL | O_CREAT)

Perl's sysopen is a function equivalent to C's fopen. Specify the file handle in the first argument, the file name in the second argument, and the open flag in the third argument. If you want, you can specify the permission in octal as the 4th argument, and the default permission is 0666.

You can specify multiple open flags by connecting them with bit operator |. Specify the open mode with a combination of open flags.

For example, let's say you want to create a file if it doesn't exist and open it in write mode.

With the open function, I want to open in write mode, but I can't realize the operation of not overwriting if the file exists. You can achieve this by specifying O_WRONLY | O_EXCL | O_CREAT as open mode.

O_WRONLY means write mode, and O_CREAT means create a new file if it doesn't exist. O_EXCL means error if the file exists. O_EXCL takes precedence over O_CREAT and an error will occur if the file exists. If it does not exist, it will be created.

In order to use the symbol that represents the open flag, it must be imported in advance.

use Fcntl;

Fcntl module allows you to use symbols such as O_WRONLY. When using the sysopen function, remember to use it as a set.

Open mode type

O_RDONLY Read
O_WRONLY write in
O_RDWR Read/write
O_CREAT Create the file if it does not exist.
O_EXCL Fail open if the file exists
O_APPEND Additional writing
O_TRUNC Truncate the file to 0 bytes

Perl's open function allows you to specify the open mode using easy-to-understand symbols such as "<", ">", ">>", but on the other hand, you can specify the open mode in detail like the C language open function. can not do.

You can use the sysopen function to specify the open mode in detail. (Although you can specify permissions as well, I'll mention them when writing about file permissions.)

Example

This is an example that specifies the open mode in detail.

use strict;
use warnings;

# Module for specifying open mode with a symbol
use Fcntl;

my $file = shift; # Specify the file name.

# Create the file if it doesn't exist and open it in write mode
sysopen(my $fh, $file, O_WRONLY | O_EXCL | O_CREAT)
  or die "Couldn't open $file:$!";
close($fh);

Related Informatrion