[英]Convert long filename to short filename (8.3)
我想將長文件名/路徑轉換為短文件名(8.3)。 我正在開發一個調用命令行工具的腳本,該工具只接受短文件名。
所以我需要轉換
C:\\Ruby193\\bin\\test\\New Text Document.txt
至
C:\\Ruby193\\bin\\test\\NEWTEX~1.TXT
到目前為止,我發現如何從ARGV獲取長文件名,它使用WIN32API將短文件名轉換為長文件名(與我想要實現的相反)。
有沒有辦法在Ruby中獲取短文件名?
你可以用FFI做到這一點; 實際上有一個例子涵蓋了他們的wiki中標題為“將路徑轉換為8.3樣式路徑名”的確切場景:
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
此ruby代碼使用getShortPathName ,不需要安裝其他模塊。
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
您需要的Windows功能是GetShortPathName 。 您可以按照鏈接帖子中描述的相同方式使用它。
編輯:GetShortPathName的示例用法(僅作為簡單示例) - 短名稱將包含“C:\\ LONGFO~1 \\ LONGFI~1.TXT”,返回值為24。
TCHAR* longname = "C:\\long folder name\\long file name.txt";
TCHAR* shortname = new TCHAR[256];
GetShortPathName(longname,shortname,256);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.