1

我正在为草图编写插件。我找不到从My DocumentsWindows 目录附加文本文件的简单方法。我遇到的问题是:

  • 使用当前用户名打开
  • Windows 版本之间的差异。

我需要代码在My Documents32 位机器上的 Windows 7 上以附加模式打开文件。

4

2 回答 2

2

您可以在 Ruby 中使用反引号 ` 对系统运行命令行。然后它将返回调用的结果。

这是Ruby-Doc.org上的官方描述

返回在子 shell 中运行 cmd 的标准输出。内置语法 %x{...} 使用此方法。设置 $? 到进程状态。

`echo` #=> 'ECHO is on.' if ran on Windows

在 Windows 中,您可以使用一些特殊变量来收集用户名等信息:

echo %username%

因此,您可以使用这两个来收集用户的“我的文档”文件夹的位置(前提是它们在 Windows 上)。

# Tested on Windows XP and 7
my_documents = File.join(`echo %userprofile%`.chomp, "My Documents")

注意: Ruby 中还有一个方法可以进行系统调用,即system. 但是,这会返回一个布尔值,在您的情况下不起作用。

另请注意,此解决方案适用于 Windows。

于 2013-01-30T16:55:50.767 回答
1
file = File.open(ENV['userprofile'] + "\\My Documents\\file.txt", "a")
file.puts "text to append"
file.close

编辑:
用户文档的默认位置是:

在 Windows 98 和 Windows Me
C:\My Documents
上 在 Windows 2000 和 Windows XP
%USERPROFILE%\My Documents
上 在 Windows Vista 和更高版本上
%USERPROFILE%\Documents

Windows XP更早版本的非英语版本将使用适合该语言的目录名称。

您可以在 Windows 注册表中找到非英语系统上的正确路径:

require 'win32/registry'
reg_path = 'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
reg = Win32::Registry::HKEY_CURRENT_USER.open( reg_path )
right_path = reg['Personal']    # => C:\Documents and Settings\addo\Dokumenty
于 2013-01-30T16:47:28.713 回答