How can I generate random unique temp file names?

I am trying to create a temporary file using the following code:

use File::Temp ; $tmp = File::Temp->new( TEMPLATE => 'tempXXXXX', DIR => 'mydir', SUFFIX => '.dat'); 

This creates a temporary file. Due to my resolution problem, another program cannot write to the file.

So I just want to generate a file name without creating a file. Is there any where to do this?

+4
source share
4 answers

If you do not create a file at the same time, you create a name, then you can create a file with the same name before manually creating the file. If you need to open another file, just close it first:

 #!/usr/bin/perl use strict; use warnings; use File::Temp; sub get_temp_filename { my $fh = File::Temp->new( TEMPLATE => 'tempXXXXX', DIR => 'mydir', SUFFIX => '.dat', ); return $fh->filename; } my $filename = get_temp_filename(); open my $fh, ">", $filename or die "could not open $filename: $!"; 

The best way to deal with the permission problem is to make sure that the users who run both programs are in the same group. Then you can use chmod to change permissions inside the first program so that the second program (or any user in this group) changes the file:

 my $filename = get_temp_filename(); chmod 0660, $filename; 
+9
source

Just to get the name of a temporary file you can do:

 #!/usr/bin/perl use strict; use warnings; use 5.10.1; use File::Temp qw/tempfile/; my $file; (undef, $file) = tempfile('tmpXXXXXX', OPEN=>0); say $file; 

But like an hour. Owens said, be careful that the same name can be created before you use it.

+7
source

The get_temp_filename function proposed by the Hour. Owens uses a local file descriptor object ($ fh), which is destroyed when the function returns, which destroys the created tempfile.

To avoid this and therefore save the file (less risk):

 UNLINK => 0 

to the arguments to the new method, which prohibit the cancellation of the file during the removal of the object.

+4
source

Actually, I agree with Chas.Owens - the design is deadly corrupted.

It seems you need to fix the design, so:

If you have control over the 2nd program, create a file and transfer the file name to the 1st program.


But if the 2nd program is not what you wrote, and therefore you cannot change it, I would recommend one of the following:

1 - Use the first PID process as part of the file name to minimize the risk of duplicate file names.

2 - Make the 2nd program channel your access to the 1st program, do not bother the file at all. Personally, this is a much better solution than 1.

3 - Wrap the second program in a script (shell, perl, whatever) that creates the name and file and passes them to both programs.

+1
source

All Articles