打开文件.
file := FileOpen(Filename, Flags [, Encoding])
要打开文件的路径, 如果未指定绝对路径则假定在 %A_WorkingDir% 中.
[在 AHK_L 54+] 表示希望使用的访问模式的字符串, 后面跟着其他选项 (中间可以含有空格或 tab); 或 [在 AHK_L 42+] 数值标志的组合 (总和). 下表中描述了支持的值.
当文件没有包含 UTF-8 或 UTF-16 字节顺序标记时文件 I/O 使用的代码页.
如果省略, 则使用 A_FileEncoding 的当前值.
| 访问模式 (互斥的) | ||
|---|---|---|
| r | 0 | 读取: 当文件不存在时失败. |
| w | 1 | 写入:创建新文件,若文件已存在则覆盖它们。 |
| a | 2 | 追加: 如果文件不存在则创建新文件, 否则移动文件指针到文件末尾. |
| rw | 3 | 读取/写入: 当文件不存在时创建新文件. |
| h | 表示 Filename 是包装在对象中的文件句柄. 忽略共享模式标志. 当文件对象销毁时, 文件句柄 不会 自动关闭并且调用 Close 没有效果. 注意当 Filename 是到非搜寻设备 (例如管道或通信设备) 的句柄时不应该使用 Seek, Tell 和 Length. | |
| 共享模式标志 | ||
| -rwd | 为读取, 写入和/或删除访问进行文件锁定. 可以使用 r, w 和 d 的任意组合. 指定 - 相当于指定 -rwd. 如果完全省略, 默认为共享所有访问. | |
| 0 | 如果 Flags 是数值的, 缺少共享模式标志会让文本被锁定. | |
| 0x100 | 共享 读取 访问. | |
| 0x200 | 共享 写入 访问. | |
| 0x400 | 共享 删除 访问. | |
| 行结束符 (EOL) 选项 | ||
`n | 4 | 读取时把 `r`n 替换为 `n 而写入时把 `n 替换为 `r`n. |
`r | 8 | 读取时把单独的 `r 替换为 `n. |
如果成功打开文件, 则返回值为 文件对象.
如果函数失败, 则返回值为 0 且 [in AHK_L 54+] A_LastError 包含错误码.
使用 if file 或 IsObject(file) 可以判断函数是否成功执行.
当创建 UTF-8 或 UTF-16 文件时, 会写入字节顺序标记到文件中, 除非 Encoding (或 A_FileEncoding, 当 Encoding 省略时) 包含 "UTF-8-RAW" 或 "UTF-16-RAW".
以读取方式打开含有 UTF-8 或 UTF-16 字节顺序标记(BOM)的文件时,会把文件指针放置到这个标志后来从输出中排除 BOM。因此,在刚刚打开这样的文件时 File.Position 可能为 3 或 2。
; 示例: 这是个可运行脚本, 它写入一些文本到文件, 然后从文件读取回内存.
; 它提供了与 此 DllCall 示例 同样的功能.
FileSelectFile, FileName, S16,, Create a new file:
if (FileName = "")
return
file := FileOpen(FileName, "w")
if !IsObject(file)
{
MsgBox Can't open "%FileName%" for writing.
return
}
TestString := "This is a test string.`r`n" ; 通过这种方式写入内容到文件时, 要使用 `r`n 而不是 `n 来开始新行.
file.Write(TestString)
file.Close()
; 现在已经把内容写入文件了, 重新把它们读取回内存中.
file := FileOpen(FileName, "r-d") ; 读取文件 ("r"), 共享除删除 ("-d") 外的所有访问权限
if !IsObject(file)
{
MsgBox Can't open "%FileName%" for reading.
return
}
CharsToRead := StrLen(TestString)
TestString := file.Read(CharsToRead)
file.Close()
MsgBox The following string was read from the file: %TestString%
; 以只读模式打开脚本并读取它的首行:
file := FileOpen(A_ScriptFullPath, "r")
MsgBox % file.ReadLine()
; 打开控制台窗口以进行此次演示:
DllCall("AllocConsole")
; 在新行符转换模式中打开应用程序的 stdin/stdout 句柄.
stdin := FileOpen(DllCall("GetStdHandle", "int", -10, "ptr"), "h `n")
stdout := FileOpen(DllCall("GetStdHandle", "int", -11, "ptr"), "h `n")
stdout.Write("Enter your query.`n\> ")
stdout.Read(0) ; 刷新写入缓冲区.
query := RTrim(stdin.ReadLine(), "`n")
stdout.WriteLine("Your query was '" query "'. Have a nice day.")
stdout.Read(0) ; 刷新写入缓冲区.
Sleep 5000