File::Temp - return name and handle of a temporary file safely
use File::Temp qw/ tempfile tempdir /;
$fh = tempfile(); ($fh, $filename) = tempfile();
($fh, $filename) = tempfile( $template, DIR => $dir); ($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
$dir = tempdir( CLEANUP => 1 ); ($fh, $filename) = tempfile( DIR => $dir );
Object interface:
require File::Temp; use File::Temp ();
$fh = new File::Temp($template); $fname = $fh->filename;
$tmp = new File::Temp( UNLINK => 0, SUFFIX => '.dat' ); print $tmp "Some data\n"; print "Filename is $tmp\n";
The following interfaces are provided for compatibility with existing APIs. They should not be used in new code.
MkTemp family:
use File::Temp qw/ :mktemp /;
($fh, $file) = mkstemp( "tmpfileXXXXX" ); ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
$tmpdir = mkdtemp( $template );
$unopened_file = mktemp( $template );
POSIX functions:
use File::Temp qw/ :POSIX /;
$file = tmpnam(); $fh = tmpfile();
($fh, $file) = tmpnam();
Compatibility functions:
$unopened_file = File::Temp::tempnam( $dir, $pfx );
The security aspect of temporary file creation is emphasized such that a filehandle and filename are returned together. This helps guarantee that a race condition can not occur where the temporary file is created by another process between checking for the existence of the file and its opening. Additional security levels are provided to check, for example, that the sticky bit is set on world writable directories. See ``safe_level'' for more information.
For compatibility with popular C library functions, Perl implementations of the mkstemp() family of functions are provided. These are, mkstemp(), mkstemps(), mkdtemp() and mktemp().
Additionally, implementations of the standard POSIX tmpnam() and tmpfile() functions are provided if required.
Implementations of mktemp(), tmpnam(), and tempnam() are provided, but should be used with caution since they return only a filename that was valid when function was called, so cannot guarantee that the file will not exist by the time the caller opens the filename.
Note that there is no method to obtain the filehandle from the "File::Temp" object. The object itself acts as a filehandle. Also, the object is configured such that it stringifies to the name of the temporary file.
my $tmp = new File::Temp();
by default the object is constructed as if "tempfile" was called without options, but with the additional behaviour that the temporary file is removed by the object destructor if UNLINK is set to true (the default).
Supported arguments are the same as for "tempfile": UNLINK (defaulting to true), DIR and SUFFIX. Additionally, the filename template is specified using the TEMPLATE option. The OPEN option is not supported (the file is always opened).
$tmp = new File::Temp( TEMPLATE => 'tempXXXXX', DIR => 'mydir', SUFFIX => '.dat');
Arguments are case insensitive.
$filename = $tmp->filename;
This method is called automatically when the object is used as a string.
$fh->unlink_on_destroy( 1 );
Default is for the file to be removed.
No error is given if the unlink fails.
If the global variable $KEEP_ALL is true, the file will not be removed.
$fh = tempfile(); ($fh, $filename) = tempfile();
Create a temporary file in the directory specified for temporary files, as specified by the tmpdir() function in File::Spec.
($fh, $filename) = tempfile($template);
Create a temporary file in the current directory using the supplied template. Trailing `X' characters are replaced with random letters to generate the filename. At least four `X' characters must be present at the end of the template.
($fh, $filename) = tempfile($template, SUFFIX => $suffix)
Same as previously, except that a suffix is added to the template after the `X' translation. Useful for ensuring that a temporary filename has a particular extension when needed by other applications. But see the WARNING at the end.
($fh, $filename) = tempfile($template, DIR => $dir);
Translates the template as before except that a directory name is specified.
($fh, $filename) = tempfile($template, UNLINK => 1);
Return the filename and filehandle as before except that the file is automatically removed when the program exits (dependent on $KEEP_ALL). Default is for the file to be removed if a file handle is requested and to be kept if the filename is requested. In a scalar context (where no filename is returned) the file is always deleted either (depending on the operating system) on exit or when it is closed (unless $KEEP_ALL is true when the temp file is created).
Use the object-oriented interface if fine-grained control of when a file is removed is required.
If the template is not specified, a template is always automatically generated. This temporary file is placed in tmpdir() (File::Spec) unless a directory is specified explicitly with the DIR option.
$fh = tempfile( $template, DIR => $dir );
If called in scalar context, only the filehandle is returned and the file will automatically be deleted when closed on operating systems that support this (see the description of tmpfile() elsewhere in this document). This is the preferred mode of operation, as if you only have a filehandle, you can never create a race condition by fumbling with the filename. On systems that can not unlink an open file or can not mark a file as temporary when it is opened (for example, Windows NT uses the "O_TEMPORARY" flag) the file is marked for deletion when the program ends (equivalent to setting UNLINK to 1). The "UNLINK" flag is ignored if present.
(undef, $filename) = tempfile($template, OPEN => 0);
This will return the filename based on the template but will not open this file. Cannot be used in conjunction with UNLINK set to true. Default is to always open the file to protect from possible race conditions. A warning is issued if warnings are turned on. Consider using the tmpnam() and mktemp() functions described elsewhere in this document if opening the file is not required.
Options can be combined as required.
$tempdir = tempdir();
Create a directory in tmpdir() (see File::Spec).
$tempdir = tempdir( $template );
Create a directory from the supplied template. This template is similar to that described for tempfile(). `X' characters at the end of the template are replaced with random letters to construct the directory name. At least four `X' characters must be in the template.
$tempdir = tempdir ( DIR => $dir );
Specifies the directory to use for the temporary directory. The temporary directory name is derived from an internal template.
$tempdir = tempdir ( $template, DIR => $dir );
Prepend the supplied directory name to the template. The template should not include parent directory specifications itself. Any parent directory specifications are removed from the template before prepending the supplied directory.
$tempdir = tempdir ( $template, TMPDIR => 1 );
Using the supplied template, create the temporary directory in a standard location for temporary files. Equivalent to doing
$tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);
but shorter. Parent directory specifications are stripped from the template itself. The "TMPDIR" option is ignored if "DIR" is set explicitly. Additionally, "TMPDIR" is implied if neither a template nor a directory are supplied.
$tempdir = tempdir( $template, CLEANUP => 1);
Create a temporary directory using the supplied template, but attempt to remove it (and all files inside it) when the program exits. Note that an attempt will be made to remove all files from the directory even if they were not created by this module (otherwise why ask to clean it up?). The directory removal is made with the rmtree() function from the File::Path module. Of course, if the template is not specified, the temporary directory will be created in tmpdir() and will also be removed at program exit.
($fh, $name) = mkstemp( $template );
In scalar context, just the filehandle is returned.
The template may be any filename with some number of X's appended to it, for example /tmp/temp.XXXX. The trailing X's are replaced with unique alphanumeric combinations.
($fh, $name) = mkstemps( $template, $suffix );
For example a template of "testXXXXXX" and suffix of ".dat" would generate a file similar to testhGji_w.dat.
Returns just the filehandle alone when called in scalar context.
$tmpdir_name = mkdtemp($template);
Returns the name of the temporary directory created. Returns undef on failure.
Directory must be removed by the caller.
$unopened_file = mktemp($template);
Template is the same as that required by mkstemp().
Unlike the POSIX implementations, the directory used for the temporary file is not specified in a system include file ("P_tmpdir") but simply depends on the choice of tmpdir() returned by File::Spec. On some implementations this location can be set using the "TMPDIR" environment variable, which may not be secure. If this is a problem, simply use mkstemp() and specify a template.
$file = tmpnam();
When called in list context, a filehandle to the open file and a filename are returned. This is achieved by calling mkstemp() after constructing a suitable template.
($fh, $file) = tmpnam();
If possible, this form should be used to prevent possible race conditions.
See ``tmpdir'' in File::Spec for information on the choice of temporary directory for a particular operating system.
$fh = tmpfile();
The file is removed when the filehandle is closed or when the program exits. No access to the filename is provided.
If the temporary file can not be created undef is returned. Currently this command will probably not work when the temporary directory is on an NFS file system.
They are not exported and must be addressed using the full package name.
$filename = File::Temp::tempnam( $dir, $prefix );
Equivalent to running mktemp() with $dir/$prefixXXXXXXXX (using unix file convention as an example)
Because this function uses mktemp(), it can suffer from race conditions.
unlink0($fh, $path) or die "Error unlinking file $path safely";
Returns false on error. The filehandle is not closed since on some occasions this is not required.
On some platforms, for example Windows NT, it is not possible to unlink an open file (the file must be closed first). On those platforms, the actual unlinking is deferred until the program ends and good status is returned. A check is still performed to make sure that the filehandle and filename are pointing to the same thing (but not at the time the end block is executed since the deferred removal may not have access to the filehandle).
Additionally, on Windows NT not all the fields returned by stat() can be compared. For example, the "dev" and "rdev" fields seem to be different. Also, it seems that the size of the file returned by stat() does not always agree, with "stat(FH)" being more accurate than "stat(filename)", presumably because of caching issues even when using autoflush (this is usually overcome by waiting a while after writing to the tempfile before attempting to "unlink0" it).
Finally, on NFS file systems the link count of the file handle does not always go to zero immediately after unlinking. Currently, this command is expected to fail on NFS disks.
This function is disabled if the global variable $KEEP_ALL is true and an unlink on open file is supported. If the unlink is to be deferred to the END block, the file is still registered for removal.
cmpstat($fh, $path) or die "Error comparing handle with file";
Returns false if the stat information differs or if the link count is greater than 1.
On certain platofms, eg Windows, not all the fields returned by stat() can be compared. For example, the "dev" and "rdev" fields seem to be different in Windows. Also, it seems that the size of the file returned by stat() does not always agree, with "stat(FH)" being more accurate than "stat(filename)", presumably because of caching issues even when using autoflush (this is usually overcome by waiting a while after writing to the tempfile before attempting to "unlink0" it).
Not exported by default.
unlink1($fh, $path) or die "Error closing and unlinking file";
Usually called from the object destructor when using the OO interface.
Not exported by default.
This function is disabled if the global variable $KEEP_ALL is true.
On OSes where temp files are automatically removed when the temp file is closed, calling this function will have no effect other than to remove temporary directories (which may include temporary files).
File::Temp::cleanup();
Not exported by default.
Will not work on platforms that do not support the "-k" test for sticky bit.
For platforms that do not support the POSIX "_PC_CHOWN_RESTRICTED" symbol (for example, Windows NT) it is assumed that ``chown() giveaway'' is possible and the recursive test is performed.
The level can be changed as follows:
File::Temp->safe_level( File::Temp::HIGH );
The level constants are not exported by the module.
Currently, you must be running at least perl v5.6.0 in order to run with MEDIUM or HIGH security. This is simply because the safety tests use functions from Fcntl that are not available in older versions of perl. The problem is that the version number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though they are different versions.
On systems that do not support the HIGH or MEDIUM safety levels (for example Win NT or OS/2) any attempt to change the level will be ignored. The decision to ignore rather than raise an exception allows portable programs to be written with high security in mind for the systems that can support this without those programs failing on systems where the extra tests are irrelevant.
If you really need to see whether the change has been accepted simply examine the return value of "safe_level".
$newlevel = File::Temp->safe_level( File::Temp::HIGH ); die "Could not change to high security" if $newlevel != File::Temp::HIGH;
This is required since on many unix systems "/tmp" is not owned by root.
Default is to assume that any UID less than or equal to 10 is a root UID.
File::Temp->top_system_uid(10); my $topid = File::Temp->top_system_uid;
This value can be adjusted to reduce security checking if required. The value is only relevant when "safe_level" is set to MEDIUM or higher.
$File::Temp::KEEP_ALL = 1;
Default is for files to be removed as requested by the caller.
In some cases, files will only be retained if this variable is true when the file is created. This means that you can not create a temporary file, set this variable and expect the temp file to still be around when the program exits.
$File::Temp::DEBUG = 1;
Default is for debugging mode to be disabled.
If you need to pass the handle to something that expects a filename then, on a unix system, use ""/dev/fd/" . fileno($fh)" for arbitrary programs, or more generally ""+<=&" . fileno($fh)" for Perl programs. You will have to clear the close-on-exec bit on that file descriptor before passing it to another process.
use Fcntl qw/F_SETFD F_GETFD/; fcntl($tmpfh, F_SETFD, 0) or die "Can't clear close-on-exec flag on temp fh: $!\n";
See IO::File and File::MkTemp, Apachae::TempFile for different implementations of temporary file handling.
Copyright (C) 1999-2005 Tim Jenness and the UK Particle Physics and Astronomy Research Council. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Original Perl implementation loosely based on the OpenBSD C code for mkstemp(). Thanks to Tom Christiansen for suggesting that this module should be written and providing ideas for code improvements and security enhancements.
Закладки на сайте Проследить за страницей |
Created 1996-2024 by Maxim Chirkov Добавить, Поддержать, Вебмастеру |