Ruby - DOS (Win32) 路径名到 NT( native )路径名

标签 ruby pathname

我需要从 Ruby (1.9.3) 中的 DOS (Win32) 路径获取文件的 NT( native )路径。

意思是,我有字符串:

dos_path = "C:\Windows\regedit.exe"

但我需要:

nt_path = "\Device\HarddiskVolume1\Windows\regedit.exe"

有什么办法吗? 谢谢!

最佳答案

可以使用 QueryDosDevice 将 MS-DOS 设备名称转换为 NT 路径功能。从 Ruby 调用这样的函数可以用 Fiddle 完成。 .从 1.9.3 开始,它是 Ruby 标准库的一部分。但是,以下示例仅适用于 2.0.0 或更新版本。

require 'fiddle/import'
require 'fiddle/types'

module DOS2NT
  extend Fiddle::Importer # makes function importing easier
  dlload 'kernel32.dll'
  include Fiddle::Win32Types # so DWORD can be used instead of unsigned long
  extern 'DWORD QueryDosDeviceW(void*, void*, DWORD)', :stdcall
  extern 'DWORD GetLastError()', :stdcall
  ERROR_INSUFFICIENT_BUFFER = 122

  SIZEOF_WCHAR = 2 # sizeof(WCHAR) on Windows

  # a generic error class
  class Error < StandardError
  end

  def self.dos_device_name_to_path(devicename)
    initial_len = 256
    grow_factor = 2
    # we care about Unicode (Windows uses UTF-16LE)
    devicename.encode!(Encoding::UTF_16LE)
    # create buffer
    buf = "\0\0".force_encoding(Encoding::UTF_16LE) * initial_len
    # call QueryDosDeviceW until the call was successful
    while (written_chars = QueryDosDeviceW(devicename, buf, buf.length)) == 0
      # it wasn't
      case (error = GetLastError())
      # resize buffer as it was too short
      when ERROR_INSUFFICIENT_BUFFER
        buf *= grow_factor
      # other errors like ERROR_FILE_NOT_FOUND (2)
      else
        raise Error, "QueryDosDeviceW failed (GetLastError returned #{error})"
      end
    end
    # truncate buffer (including the null character)
    path = buf[0, written_chars - SIZEOF_WCHAR]
    # transcode the path to UTF-8 as that's usually more useful
    path.encode!(Encoding::UTF_8)
  end
end
# example strings from the question
dos_path = 'C:\Windows\regedit.exe'
nt_path = '\Device\HarddiskVolume1\Windows\regedit.exe'
# convert and print inspected result
p dos_path.sub(/\A[A-Z]:/i) { |m| DOS2NT.dos_device_name_to_path(m) } # => "\\Device\\HarddiskVolume1\\Windows\\regedit.exe"

关于Ruby - DOS (Win32) 路径名到 NT( native )路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31814555/

相关文章:

ruby - Directory的mkdir和新方法之间的区别

ruby-on-rails - 事件记录查询忽略零值

javascript - 如果当前 URL 是主页,请执行某些操作

ruby - 如何在 Rails 4.1 中只在路由上写入一次 path_names 并使其可用于所有路由?

ruby-on-rails - 使用常规持久性方法通过 mongoid 更新 Rails 模型的属性

ruby - 仅对数组中的整数求和(Ruby)

ruby-on-rails - 在 OSX catalina(10.15.1) 中使用 rbenv 安装 ruby​​-2.4.0 时构建失败(OS X 10.15.1 使用 ruby​​-build 20191124)

Linux,用 bash 'no such file or directory' 错误重命名文件

json - Linux CLI - 如何从 JSON jq + grep 获取子字符串?