Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: "unique" filename?

by Fastolfe (Vicar)
on Dec 03, 2000 at 22:17 UTC ( [id://44687]=note: print w/replies, xml ) Need Help??


in reply to "unique" filename?

For generating, say, unique temporary files, use IO::File::new_tmpfile. In addition there's the POSIX::tmpnam() function which would get you a unique filename (subject to a race condition, however, since there's a period between when it's generated and when it's used).

In a pinch, use something like this:

$num = 12345; $dir = "/some/dir/"; $num++ while -e "$dir/$num"; open(F, ">$dir/$num") or die ...
But of course, there's still a race condition. A more secure solution would be to take advantage of sysopen and O_EXCL to iterate through filenames:
use Fcntl; use FileHandle; $num++ while !sysopen(F, "$dir/$num", O_EXCL|O_CREAT, 0777) && $! eq " +File exists"; die "$dir/$num: $!" if $!;
Once you start adding all of the bells and whistles, though, you're just re-implementing IO::File new_tmpfile.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://44687]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-25 10:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found