lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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.
> 
> Dirk

Hi all,

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.

function open_temp_file()
	local handle
	local fname
	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")
			break
		end
		io.close(handle)
		io.write(".")   -- Shows collision, comment out except for diagnostics
	end
	return handle, fname
end

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.

Thanks

SteveT

Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt