Ruby, Win32, GetFileAttributesEx()

RubyでWin32 APIを叩いて、File.sizeできちんと取得できない*1、でかいファイルのサイズを得る。

require 'Win32API'

getFileAttributesEx = Win32API.new('kernel32.dll', 'GetFileAttributesEx', %(p n p), 'i')

filePath = 'big_file.bin'

#APIがデータを書き込む構造体を用意する。
info = "\0" * 36
result = getFileAttributesEx.call(filePath, 0, info)
if (result != 0) then
    #構造体は{DWORD, {DWORD, DWORD}, {DWORD, DWORD}, {DWORD, DWORD}, DWORD, DWORD}という形。
    #必要なのは、最後の二つのDWORDの値。
    ary = info.unpack('A28 L L')
    print "High = #{ary[1]}\n"
    print "Low  = #{ary[2]}\n"
    sz = ary[1] * 0x100000000 + ary[2] #ary[1] * 0x100000000 + ary[2] がファイルサイズとなる。
    print "Size = #{sz}\n"
end

*1:64bit OSになったらいけるかな?