我正在为草图编写插件。我找不到一种简单的方法来附加Windows上My Documents
目录中的文本文件。我遇到的问题是:
我需要代码在32位计算机上的Windows 7上的My Documents
中以附加模式打开文件。
答案 0 :(得分:2)
您可以使用Ruby中的反引号来对系统运行命令行。然后它将返回调用的结果。
以下是Ruby-Doc.org
的官方说明返回子shell中运行cmd的标准输出。内置 语法%x {...}使用此方法。设置$?进程状态。
`echo` #=> 'ECHO is on.' if ran on Windows
在Windows中,您可以使用special variables来收集用户名等信息:
echo %username%
因此,您可以使用这两个来收集用户的“我的文档”文件夹的位置(前提是它们在Windows上)。
# Tested on Windows XP and 7
my_documents = File.join(`echo %userprofile%`.chomp, "My Documents")
注意:强>
Ruby中还有一个方法可以进行system
的系统调用。但是,这会返回一个布尔值,在您的情况下不起作用。
另请注意,此解决方案仅可在Windows上运行。
答案 1 :(得分:1)
file = File.open(ENV['userprofile'] + "\\My Documents\\file.txt", "a")
file.puts "text to append"
file.close
修改强>
Default location of user's documents 是:
在Windows 98和Windows Me上
C:\My Documents
在Windows 2000和Windows XP上
%USERPROFILE%\My Documents
在Windows Vista及更高版本中
%USERPROFILE%\Documents
非英语版本 Windows XP 或早期将使用目录名称 适合那种语言。
You can find the right path在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