[Win32utils-devel] _mktemp on Windows

Daniel Berger djberg96 at gmail.com
Tue Jan 17 21:30:41 EST 2012


On Tue, Jan 17, 2012 at 5:47 PM, Heesob Park <phasis at gmail.com> wrote:
> Hi,
>
> 2012/1/18 Daniel Berger <djberg96 at gmail.com>:
>> On Tue, Jan 17, 2012 at 11:36 AM, Daniel Berger <djberg96 at gmail.com> wrote:
>>> On Tue, Jan 17, 2012 at 5:00 AM, Heesob Park <phasis at gmail.com> wrote:
>>>> Hi,
>>>>
>>>> 2012/1/14 Daniel Berger <djberg96 at gmail.com>:
>>>>> Is it odd that calling _mktemp more than once in the same process doesn't work?
>>>>>
>>>>> require 'ffi'
>>>>>
>>>>> class Win
>>>>>  extend FFI::Library
>>>>>
>>>>>  ffi_lib 'msvcrt'
>>>>>  attach_function :_mktemp, [:string], :string
>>>>>
>>>>>  def self.mktemp
>>>>>    5.times{ p _mktemp("rb_file_temp_XXXXXX") }
>>>>>  end
>>>>> end
>>>>>
>>>>> Win.mktemp
>>>>>
>>>>> # Output
>>>>> "rb_file_temp_a03680"
>>>>> nil
>>>>> nil
>>>>> nil
>>>>> nil
>>>>
>>>> Here is a proper working version:
>>>>
>>>>
>>>> require 'ffi'
>>>>
>>>> class Win
>>>>  extend FFI::Library
>>>>
>>>>  ffi_lib 'msvcrt'
>>>>  attach_function :_mktemp, [:pointer], :string
>>>>
>>>>  def self.mktemp
>>>>  5.times {
>>>>   buf = FFI::MemoryPointer.from_string("rb_file_temp_XXXXXX")
>>>>   p _mktemp(buf)
>>>>  }
>>>>  end
>>>> end
>>>>
>>>> Win.mktemp
>>>
>>> That's better, though it seems to return the same string each time
>>> instead of providing a new one. I get:
>>>
>>> "rb_file_temp_a03200"
>>> "rb_file_temp_a03200"
>>> "rb_file_temp_a03200"
>>> "rb_file_temp_a03200"
>>> "rb_file_temp_a03200"
>>
>> Actually, I get the same result with the C code that MS provides, too.
>>
>> I think I might be better off writing a custom mktemp method in pure Ruby.
>>
> I guess you overlooked the C code that MS provides, it created file
> with temp names.
> If you want the same result with the C code, here is a modified version:
>
> require 'ffi'
>
> class Win
>  extend FFI::Library
>
>  ffi_lib 'msvcrt'
>  attach_function :_mktemp, [:pointer], :string
>
>  def self.mktemp
>  5.times {
>   buf = FFI::MemoryPointer.from_string("rb_file_temp_XXXXXX")
>   p res = _mktemp(buf)
>   File.open(res,"w")
>  }
>  end
> end
>
> Win.mktemp
>
> #output
> "rb_file_temp_a03144"
> "rb_file_temp_b03144"
> "rb_file_temp_c03144"
> "rb_file_temp_d03144"
> "rb_file_temp_e03144"

Oh, I see. It doesn't actually create a unique name unless the file is
actually created. It doesn't just automatically bump the name.

Thanks,

Dan


More information about the win32utils-devel mailing list