[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Can I template the filename for io.tmpfile() <SOLVED VIA WORKAROUND>
- From: Steve Litt <slitt@...>
- Date: Fri, 14 Jan 2011 07:59:56 -0500
On Wednesday 12 January 2011 02:17:54 Dirk Laurie wrote:
> On Wed, Jan 12, 2011 at 08:34:37AM +0200, Steve Litt wrote:
> > The docs on io.tmpfile are pretty sparse, and before I roll my own let me
> > ask.
> A quick look at liolib.c reveals that io.tmpfile makes use of
> the tmpfile() function in C (provided in stdio.h) and that you
> therefore have absolutely no option to customize it in any way.
As Dirk mentioned, there's no way to template a tempfile name, and that's what
I needed. Unlike io.tmpfile(), I also needed to acquire the name for later
use. I could have os.execute()ed Linux mktemp, but that's slower than I
wanted, and it's a little ugly.
So I made a workaround which has ever so slight a chance of failure, but
because I open for write the moment I find no file with the proposed filename,
this slight chance is minimized.
while true do
fname = "yourfile" .. tostring(math.random(11111111,99999999) .. ".fil")
handle = io.open(fname, "r")
if not handle then
handle = io.open(fname, "w")
io.write(".") -- Shows collision, comment out except for diagnostics
return handle, fname
It returns both a handle to the newly opened (for write) file, and its
filename. Obviously, to change the templating or even make it configurable,
you change the fname= line.
The #1 priority of the preceding code is to minimize the time between finding
that there's no file called fname, and creating the file by that name.
My testing indicates that in practice less than 1 in 2000 invocations of this
functions requires more than a single trip through the loop, and those tests
were done creating and not deleting 40,000 such files. Also, in my real app, I
concatted my username with os.time, making it almost impossible to run that
loop more than once in a small office environment.
Recession Relief Package