1File::Temp(3pm) Perl Programmers Reference Guide File::Temp(3pm)
2
3
4
6 File::Temp - return name and handle of a temporary file safely
7
9 use File::Temp qw/ tempfile tempdir /;
10
11 $fh = tempfile();
12 ($fh, $filename) = tempfile();
13
14 ($fh, $filename) = tempfile( $template, DIR => $dir);
15 ($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
16
17 $dir = tempdir( CLEANUP => 1 );
18 ($fh, $filename) = tempfile( DIR => $dir );
19
20 Object interface:
21
22 require File::Temp;
23 use File::Temp ();
24
25 $fh = new File::Temp($template);
26 $fname = $fh->filename;
27
28 $tmp = new File::Temp( UNLINK => 0, SUFFIX => '.dat' );
29 print $tmp "Some data\n";
30 print "Filename is $tmp\n";
31
32 The following interfaces are provided for compatibility with existing
33 APIs. They should not be used in new code.
34
35 MkTemp family:
36
37 use File::Temp qw/ :mktemp /;
38
39 ($fh, $file) = mkstemp( "tmpfileXXXXX" );
40 ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
41
42 $tmpdir = mkdtemp( $template );
43
44 $unopened_file = mktemp( $template );
45
46 POSIX functions:
47
48 use File::Temp qw/ :POSIX /;
49
50 $file = tmpnam();
51 $fh = tmpfile();
52
53 ($fh, $file) = tmpnam();
54
55 Compatibility functions:
56
57 $unopened_file = File::Temp::tempnam( $dir, $pfx );
58
60 "File::Temp" can be used to create and open temporary files in a safe
61 way. There is both a function interface and an object-oriented inter‐
62 face. The File::Temp constructor or the tempfile() function can be
63 used to return the name and the open filehandle of a temporary file.
64 The tempdir() function can be used to create a temporary directory.
65
66 The security aspect of temporary file creation is emphasized such that
67 a filehandle and filename are returned together. This helps guarantee
68 that a race condition can not occur where the temporary file is created
69 by another process between checking for the existence of the file and
70 its opening. Additional security levels are provided to check, for
71 example, that the sticky bit is set on world writable directories. See
72 "safe_level" for more information.
73
74 For compatibility with popular C library functions, Perl implementa‐
75 tions of the mkstemp() family of functions are provided. These are,
76 mkstemp(), mkstemps(), mkdtemp() and mktemp().
77
78 Additionally, implementations of the standard POSIX tmpnam() and tmp‐
79 file() functions are provided if required.
80
81 Implementations of mktemp(), tmpnam(), and tempnam() are provided, but
82 should be used with caution since they return only a filename that was
83 valid when function was called, so cannot guarantee that the file will
84 not exist by the time the caller opens the filename.
85
87 This is the primary interface for interacting with "File::Temp". Using
88 the OO interface a temporary file can be created when the object is
89 constructed and the file can be removed when the object is no longer
90 required.
91
92 Note that there is no method to obtain the filehandle from the
93 "File::Temp" object. The object itself acts as a filehandle. Also, the
94 object is configured such that it stringifies to the name of the tempo‐
95 rary file.
96
97 new Create a temporary file object.
98
99 my $tmp = new File::Temp();
100
101 by default the object is constructed as if "tempfile" was called
102 without options, but with the additional behaviour that the tempo‐
103 rary file is removed by the object destructor if UNLINK is set to
104 true (the default).
105
106 Supported arguments are the same as for "tempfile": UNLINK
107 (defaulting to true), DIR and SUFFIX. Additionally, the filename
108 template is specified using the TEMPLATE option. The OPEN option is
109 not supported (the file is always opened).
110
111 $tmp = new File::Temp( TEMPLATE => 'tempXXXXX',
112 DIR => 'mydir',
113 SUFFIX => '.dat');
114
115 Arguments are case insensitive.
116
117 filename
118 Return the name of the temporary file associated with this object.
119
120 $filename = $tmp->filename;
121
122 This method is called automatically when the object is used as a
123 string.
124
125 unlink_on_destroy
126 Control whether the file is unlinked when the object goes out of
127 scope. The file is removed if this value is true and $KEEP_ALL is
128 not.
129
130 $fh->unlink_on_destroy( 1 );
131
132 Default is for the file to be removed.
133
134 DESTROY
135 When the object goes out of scope, the destructor is called. This
136 destructor will attempt to unlink the file (using "unlink1") if the
137 constructor was called with UNLINK set to 1 (the default state if
138 UNLINK is not specified).
139
140 No error is given if the unlink fails.
141
142 If the global variable $KEEP_ALL is true, the file will not be
143 removed.
144
146 This section describes the recommended interface for generating tempo‐
147 rary files and directories.
148
149 tempfile
150 This is the basic function to generate temporary files. The behav‐
151 iour of the file can be changed using various options:
152
153 $fh = tempfile();
154 ($fh, $filename) = tempfile();
155
156 Create a temporary file in the directory specified for temporary
157 files, as specified by the tmpdir() function in File::Spec.
158
159 ($fh, $filename) = tempfile($template);
160
161 Create a temporary file in the current directory using the supplied
162 template. Trailing `X' characters are replaced with random letters
163 to generate the filename. At least four `X' characters must be
164 present at the end of the template.
165
166 ($fh, $filename) = tempfile($template, SUFFIX => $suffix)
167
168 Same as previously, except that a suffix is added to the template
169 after the `X' translation. Useful for ensuring that a temporary
170 filename has a particular extension when needed by other applica‐
171 tions. But see the WARNING at the end.
172
173 ($fh, $filename) = tempfile($template, DIR => $dir);
174
175 Translates the template as before except that a directory name is
176 specified.
177
178 ($fh, $filename) = tempfile($template, UNLINK => 1);
179
180 Return the filename and filehandle as before except that the file
181 is automatically removed when the program exits (dependent on
182 $KEEP_ALL). Default is for the file to be removed if a file handle
183 is requested and to be kept if the filename is requested. In a
184 scalar context (where no filename is returned) the file is always
185 deleted either (depending on the operating system) on exit or when
186 it is closed (unless $KEEP_ALL is true when the temp file is cre‐
187 ated).
188
189 Use the object-oriented interface if fine-grained control of when a
190 file is removed is required.
191
192 If the template is not specified, a template is always automati‐
193 cally generated. This temporary file is placed in tmpdir()
194 (File::Spec) unless a directory is specified explicitly with the
195 DIR option.
196
197 $fh = tempfile( $template, DIR => $dir );
198
199 If called in scalar context, only the filehandle is returned and
200 the file will automatically be deleted when closed on operating
201 systems that support this (see the description of tmpfile() else‐
202 where in this document). This is the preferred mode of operation,
203 as if you only have a filehandle, you can never create a race con‐
204 dition by fumbling with the filename. On systems that can not
205 unlink an open file or can not mark a file as temporary when it is
206 opened (for example, Windows NT uses the "O_TEMPORARY" flag) the
207 file is marked for deletion when the program ends (equivalent to
208 setting UNLINK to 1). The "UNLINK" flag is ignored if present.
209
210 (undef, $filename) = tempfile($template, OPEN => 0);
211
212 This will return the filename based on the template but will not
213 open this file. Cannot be used in conjunction with UNLINK set to
214 true. Default is to always open the file to protect from possible
215 race conditions. A warning is issued if warnings are turned on.
216 Consider using the tmpnam() and mktemp() functions described else‐
217 where in this document if opening the file is not required.
218
219 Options can be combined as required.
220
221 tempdir
222 This is the recommended interface for creation of temporary direc‐
223 tories. The behaviour of the function depends on the arguments:
224
225 $tempdir = tempdir();
226
227 Create a directory in tmpdir() (see File::Spec).
228
229 $tempdir = tempdir( $template );
230
231 Create a directory from the supplied template. This template is
232 similar to that described for tempfile(). `X' characters at the end
233 of the template are replaced with random letters to construct the
234 directory name. At least four `X' characters must be in the tem‐
235 plate.
236
237 $tempdir = tempdir ( DIR => $dir );
238
239 Specifies the directory to use for the temporary directory. The
240 temporary directory name is derived from an internal template.
241
242 $tempdir = tempdir ( $template, DIR => $dir );
243
244 Prepend the supplied directory name to the template. The template
245 should not include parent directory specifications itself. Any par‐
246 ent directory specifications are removed from the template before
247 prepending the supplied directory.
248
249 $tempdir = tempdir ( $template, TMPDIR => 1 );
250
251 Using the supplied template, create the temporary directory in a
252 standard location for temporary files. Equivalent to doing
253
254 $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);
255
256 but shorter. Parent directory specifications are stripped from the
257 template itself. The "TMPDIR" option is ignored if "DIR" is set
258 explicitly. Additionally, "TMPDIR" is implied if neither a tem‐
259 plate nor a directory are supplied.
260
261 $tempdir = tempdir( $template, CLEANUP => 1);
262
263 Create a temporary directory using the supplied template, but
264 attempt to remove it (and all files inside it) when the program
265 exits. Note that an attempt will be made to remove all files from
266 the directory even if they were not created by this module (other‐
267 wise why ask to clean it up?). The directory removal is made with
268 the rmtree() function from the File::Path module. Of course, if
269 the template is not specified, the temporary directory will be cre‐
270 ated in tmpdir() and will also be removed at program exit.
271
273 The following functions are Perl implementations of the mktemp() family
274 of temp file generation system calls.
275
276 mkstemp
277 Given a template, returns a filehandle to the temporary file and
278 the name of the file.
279
280 ($fh, $name) = mkstemp( $template );
281
282 In scalar context, just the filehandle is returned.
283
284 The template may be any filename with some number of X's appended
285 to it, for example /tmp/temp.XXXX. The trailing X's are replaced
286 with unique alphanumeric combinations.
287
288 mkstemps
289 Similar to mkstemp(), except that an extra argument can be supplied
290 with a suffix to be appended to the template.
291
292 ($fh, $name) = mkstemps( $template, $suffix );
293
294 For example a template of "testXXXXXX" and suffix of ".dat" would
295 generate a file similar to testhGji_w.dat.
296
297 Returns just the filehandle alone when called in scalar context.
298
299 mkdtemp
300 Create a directory from a template. The template must end in X's
301 that are replaced by the routine.
302
303 $tmpdir_name = mkdtemp($template);
304
305 Returns the name of the temporary directory created. Returns undef
306 on failure.
307
308 Directory must be removed by the caller.
309
310 mktemp
311 Returns a valid temporary filename but does not guarantee that the
312 file will not be opened by someone else.
313
314 $unopened_file = mktemp($template);
315
316 Template is the same as that required by mkstemp().
317
319 This section describes the re-implementation of the tmpnam() and tmp‐
320 file() functions described in POSIX using the mkstemp() from this mod‐
321 ule.
322
323 Unlike the POSIX implementations, the directory used for the temporary
324 file is not specified in a system include file ("P_tmpdir") but simply
325 depends on the choice of tmpdir() returned by File::Spec. On some
326 implementations this location can be set using the "TMPDIR" environment
327 variable, which may not be secure. If this is a problem, simply use
328 mkstemp() and specify a template.
329
330 tmpnam
331 When called in scalar context, returns the full name (including
332 path) of a temporary file (uses mktemp()). The only check is that
333 the file does not already exist, but there is no guarantee that
334 that condition will continue to apply.
335
336 $file = tmpnam();
337
338 When called in list context, a filehandle to the open file and a
339 filename are returned. This is achieved by calling mkstemp() after
340 constructing a suitable template.
341
342 ($fh, $file) = tmpnam();
343
344 If possible, this form should be used to prevent possible race con‐
345 ditions.
346
347 See "tmpdir" in File::Spec for information on the choice of tempo‐
348 rary directory for a particular operating system.
349
350 tmpfile
351 Returns the filehandle of a temporary file.
352
353 $fh = tmpfile();
354
355 The file is removed when the filehandle is closed or when the pro‐
356 gram exits. No access to the filename is provided.
357
358 If the temporary file can not be created undef is returned. Cur‐
359 rently this command will probably not work when the temporary
360 directory is on an NFS file system.
361
363 These functions are provided for backwards compatibility with common
364 tempfile generation C library functions.
365
366 They are not exported and must be addressed using the full package
367 name.
368
369 tempnam
370 Return the name of a temporary file in the specified directory
371 using a prefix. The file is guaranteed not to exist at the time the
372 function was called, but such guarantees are good for one clock
373 tick only. Always use the proper form of "sysopen" with "O_CREAT ⎪
374 O_EXCL" if you must open such a filename.
375
376 $filename = File::Temp::tempnam( $dir, $prefix );
377
378 Equivalent to running mktemp() with $dir/$prefixXXXXXXXX (using
379 unix file convention as an example)
380
381 Because this function uses mktemp(), it can suffer from race condi‐
382 tions.
383
385 Useful functions for dealing with the filehandle and filename.
386
387 unlink0
388 Given an open filehandle and the associated filename, make a safe
389 unlink. This is achieved by first checking that the filename and
390 filehandle initially point to the same file and that the number of
391 links to the file is 1 (all fields returned by stat() are com‐
392 pared). Then the filename is unlinked and the filehandle checked
393 once again to verify that the number of links on that file is now
394 0. This is the closest you can come to making sure that the file‐
395 name unlinked was the same as the file whose descriptor you hold.
396
397 unlink0($fh, $path)
398 or die "Error unlinking file $path safely";
399
400 Returns false on error. The filehandle is not closed since on some
401 occasions this is not required.
402
403 On some platforms, for example Windows NT, it is not possible to
404 unlink an open file (the file must be closed first). On those plat‐
405 forms, the actual unlinking is deferred until the program ends and
406 good status is returned. A check is still performed to make sure
407 that the filehandle and filename are pointing to the same thing
408 (but not at the time the end block is executed since the deferred
409 removal may not have access to the filehandle).
410
411 Additionally, on Windows NT not all the fields returned by stat()
412 can be compared. For example, the "dev" and "rdev" fields seem to
413 be different. Also, it seems that the size of the file returned by
414 stat() does not always agree, with "stat(FH)" being more accurate
415 than "stat(filename)", presumably because of caching issues even
416 when using autoflush (this is usually overcome by waiting a while
417 after writing to the tempfile before attempting to "unlink0" it).
418
419 Finally, on NFS file systems the link count of the file handle does
420 not always go to zero immediately after unlinking. Currently, this
421 command is expected to fail on NFS disks.
422
423 This function is disabled if the global variable $KEEP_ALL is true
424 and an unlink on open file is supported. If the unlink is to be
425 deferred to the END block, the file is still registered for
426 removal.
427
428 cmpstat
429 Compare "stat" of filehandle with "stat" of provided filename.
430 This can be used to check that the filename and filehandle ini‐
431 tially point to the same file and that the number of links to the
432 file is 1 (all fields returned by stat() are compared).
433
434 cmpstat($fh, $path)
435 or die "Error comparing handle with file";
436
437 Returns false if the stat information differs or if the link count
438 is greater than 1.
439
440 On certain platofms, eg Windows, not all the fields returned by
441 stat() can be compared. For example, the "dev" and "rdev" fields
442 seem to be different in Windows. Also, it seems that the size of
443 the file returned by stat() does not always agree, with "stat(FH)"
444 being more accurate than "stat(filename)", presumably because of
445 caching issues even when using autoflush (this is usually overcome
446 by waiting a while after writing to the tempfile before attempting
447 to "unlink0" it).
448
449 Not exported by default.
450
451 unlink1
452 Similar to "unlink0" except after file comparison using cmpstat,
453 the filehandle is closed prior to attempting to unlink the file.
454 This allows the file to be removed without using an END block, but
455 does mean that the post-unlink comparison of the filehandle state
456 provided by "unlink0" is not available.
457
458 unlink1($fh, $path)
459 or die "Error closing and unlinking file";
460
461 Usually called from the object destructor when using the OO inter‐
462 face.
463
464 Not exported by default.
465
466 This function is disabled if the global variable $KEEP_ALL is true.
467
468 cleanup
469 Calling this function will cause any temp files or temp directories
470 that are registered for removal to be removed. This happens auto‐
471 matically when the process exits but can be triggered manually if
472 the caller is sure that none of the temp files are required. This
473 method can be registered as an Apache callback.
474
475 On OSes where temp files are automatically removed when the temp
476 file is closed, calling this function will have no effect other
477 than to remove temporary directories (which may include temporary
478 files).
479
480 File::Temp::cleanup();
481
482 Not exported by default.
483
485 These functions control the global state of the package.
486
487 safe_level
488 Controls the lengths to which the module will go to check the
489 safety of the temporary file or directory before proceeding.
490 Options are:
491
492 STANDARD
493 Do the basic security measures to ensure the directory
494 exists and is writable, that the umask() is fixed before
495 opening of the file, that temporary files are opened only
496 if they do not already exist, and that possible race condi‐
497 tions are avoided. Finally the unlink0 function is used to
498 remove files safely.
499
500 MEDIUM In addition to the STANDARD security, the output directory
501 is checked to make sure that it is owned either by root or
502 the user running the program. If the directory is writable
503 by group or by other, it is then checked to make sure that
504 the sticky bit is set.
505
506 Will not work on platforms that do not support the "-k"
507 test for sticky bit.
508
509 HIGH In addition to the MEDIUM security checks, also check for
510 the possibility of ``chown() giveaway'' using the POSIX
511 sysconf() function. If this is a possibility, each direc‐
512 tory in the path is checked in turn for safeness, recur‐
513 sively walking back to the root directory.
514
515 For platforms that do not support the POSIX
516 "_PC_CHOWN_RESTRICTED" symbol (for example, Windows NT) it
517 is assumed that ``chown() giveaway'' is possible and the
518 recursive test is performed.
519
520 The level can be changed as follows:
521
522 File::Temp->safe_level( File::Temp::HIGH );
523
524 The level constants are not exported by the module.
525
526 Currently, you must be running at least perl v5.6.0 in order to run
527 with MEDIUM or HIGH security. This is simply because the safety
528 tests use functions from Fcntl that are not available in older ver‐
529 sions of perl. The problem is that the version number for Fcntl is
530 the same in perl 5.6.0 and in 5.005_03 even though they are differ‐
531 ent versions.
532
533 On systems that do not support the HIGH or MEDIUM safety levels
534 (for example Win NT or OS/2) any attempt to change the level will
535 be ignored. The decision to ignore rather than raise an exception
536 allows portable programs to be written with high security in mind
537 for the systems that can support this without those programs fail‐
538 ing on systems where the extra tests are irrelevant.
539
540 If you really need to see whether the change has been accepted sim‐
541 ply examine the return value of "safe_level".
542
543 $newlevel = File::Temp->safe_level( File::Temp::HIGH );
544 die "Could not change to high security"
545 if $newlevel != File::Temp::HIGH;
546
547 TopSystemUID
548 This is the highest UID on the current system that refers to a root
549 UID. This is used to make sure that the temporary directory is
550 owned by a system UID ("root", "bin", "sys" etc) rather than simply
551 by root.
552
553 This is required since on many unix systems "/tmp" is not owned by
554 root.
555
556 Default is to assume that any UID less than or equal to 10 is a
557 root UID.
558
559 File::Temp->top_system_uid(10);
560 my $topid = File::Temp->top_system_uid;
561
562 This value can be adjusted to reduce security checking if required.
563 The value is only relevant when "safe_level" is set to MEDIUM or
564 higher.
565
566 $KEEP_ALL
567 Controls whether temporary files and directories should be retained
568 regardless of any instructions in the program to remove them auto‐
569 matically. This is useful for debugging but should not be used in
570 production code.
571
572 $File::Temp::KEEP_ALL = 1;
573
574 Default is for files to be removed as requested by the caller.
575
576 In some cases, files will only be retained if this variable is true
577 when the file is created. This means that you can not create a tem‐
578 porary file, set this variable and expect the temp file to still be
579 around when the program exits.
580
581 $DEBUG
582 Controls whether debugging messages should be enabled.
583
584 $File::Temp::DEBUG = 1;
585
586 Default is for debugging mode to be disabled.
587
589 For maximum security, endeavour always to avoid ever looking at, touch‐
590 ing, or even imputing the existence of the filename. You do not know
591 that that filename is connected to the same file as the handle you
592 have, and attempts to check this can only trigger more race conditions.
593 It's far more secure to use the filehandle alone and dispense with the
594 filename altogether.
595
596 If you need to pass the handle to something that expects a filename
597 then, on a unix system, use ""/dev/fd/" . fileno($fh)" for arbitrary
598 programs, or more generally ""+<=&" . fileno($fh)" for Perl programs.
599 You will have to clear the close-on-exec bit on that file descriptor
600 before passing it to another process.
601
602 use Fcntl qw/F_SETFD F_GETFD/;
603 fcntl($tmpfh, F_SETFD, 0)
604 or die "Can't clear close-on-exec flag on temp fh: $!\n";
605
606 Temporary files and NFS
607
608 Some problems are associated with using temporary files that reside on
609 NFS file systems and it is recommended that a local filesystem is used
610 whenever possible. Some of the security tests will most probably fail
611 when the temp file is not local. Additionally, be aware that the per‐
612 formance of I/O operations over NFS will not be as good as for a local
613 disk.
614
615 Forking
616
617 In some cases files created by File::Temp are removed from within an
618 END block. Since END blocks are triggered when a child process exits
619 (unless "POSIX::_exit()" is used by the child) File::Temp takes care to
620 only remove those temp files created by a particular process ID. This
621 means that a child will not attempt to remove temp files created by the
622 parent process.
623
624 BINMODE
625
626 The file returned by File::Temp will have been opened in binary mode if
627 such a mode is available. If that is not correct, use the binmode()
628 function to change the mode of the filehandle.
629
631 Originally began life in May 1999 as an XS interface to the system
632 mkstemp() function. In March 2000, the OpenBSD mkstemp() code was
633 translated to Perl for total control of the code's security checking,
634 to ensure the presence of the function regardless of operating system
635 and to help with portability. The module was shipped as a standard part
636 of perl from v5.6.1.
637
639 "tmpnam" in POSIX, "tmpfile" in POSIX, File::Spec, File::Path
640
641 See IO::File and File::MkTemp, Apachae::TempFile for different imple‐
642 mentations of temporary file handling.
643
645 Tim Jenness <tjenness@cpan.org>
646
647 Copyright (C) 1999-2005 Tim Jenness and the UK Particle Physics and
648 Astronomy Research Council. All Rights Reserved. This program is free
649 software; you can redistribute it and/or modify it under the same terms
650 as Perl itself.
651
652 Original Perl implementation loosely based on the OpenBSD C code for
653 mkstemp(). Thanks to Tom Christiansen for suggesting that this module
654 should be written and providing ideas for code improvements and secu‐
655 rity enhancements.
656
657
658
659perl v5.8.8 2001-09-21 File::Temp(3pm)