Convert long filename to short filename (8.3)

久未见 提交于 2019-12-05 18:25:51

You can do this using FFI; there's actually an example that covers your exact scenario in their wiki under the heading "Convert a path to 8.3 style pathname":

require 'ffi'

module Win
  extend FFI::Library
  ffi_lib 'kernel32'
  ffi_convention :stdcall

  attach_function :path_to_8_3, :GetShortPathNameA, [:pointer, :pointer, :uint], :uint
end
out = FFI::MemoryPointer.new 256 # bytes
Win.path_to_8_3("c:\\program files", out, out.length)
p out.get_string # be careful, the path/file you convert to 8.3 must exist or this will be empty

This ruby code uses getShortPathName and don't need additional modules to be installed.

def get_short_win32_filename(long_name)
    require 'win32api'
    win_func = Win32API.new("kernel32","GetShortPathName","PPL"," L")
    buf = 0.chr * 256
    buf[0..long_name.length-1] = long_name
    win_func.call(long_name, buf, buf.length)
    return buf.split(0.chr).first
end

The windows function you require is GetShortPathName. You could use that in the same manner as described in your linked post.

EDIT: sample usage of GetShortPathName (just as a quick example) - shortname will contain "C:\LONGFO~1\LONGFI~1.TXT" and returned value is 24.

TCHAR* longname = "C:\\long folder name\\long file name.txt";
TCHAR* shortname = new TCHAR[256];
GetShortPathName(longname,shortname,256);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!