在 IO::CatHandle 中§
请参阅主要文档 在上下文中 了解方法 open
method open(IO::CatHandle: --> IO::CatHandle)
返回调用者。此方法的目的是仅使 CatHandle 可用于使用 IO::Handle 打开内容。您永远不必有意调用此方法。
在 IO::Handle 中§
请参阅主要文档 在上下文中 了解方法 open
method open(IO::Handle::, :, :, :, :,:, :, :,: is copy,: is copy,: is copy,: is copy,: is copy,:,: is copy,: = ,: is copy = ,Str : is copy = ,: is copy,)
在其中一种模式下打开句柄。如果打开失败,则 失败 并引发适当的异常。
有关 :$chomp、:$nl-in、:$nl-out 和 :$enc 的接受值和行为,请参阅各个方法的说明。参数的值默认为调用者的属性,如果提供了任何属性,则属性将更新为新值。指定将 :$bin 设置为 True 而不是 :$enc 以指示应以二进制模式打开句柄。将未定义值指定为 :$enc 等同于根本不指定 :$enc。同时指定定义的编码为 :$enc 和将 :$bin 设置为 true 将导致引发 X::IO::BinaryAndEncoding 异常。
打开模式默认为非独占、只读(与指定 :r 相同),并且可以通过以下参数的组合来控制
:r same as specifying :mode<ro> same as specifying nothing :w same as specifying :mode<wo>, :create, :truncate :a same as specifying :mode<wo>, :create, :append :x same as specifying :mode<wo>, :create, :exclusive :update same as specifying :mode<rw> :rw same as specifying :mode<rw>, :create :ra same as specifying :mode<rw>, :create, :append :rx same as specifying :mode<rw>, :create, :exclusive
参数 :r 与 :w、:a、:x 完全相同,与上表中最后三行的字母组合相同。对上述列表之外的模式组合的支持取决于实现,并且应该假定不支持。也就是说,例如指定 .open(:r :create) 或 .open(:mode<wo> :append :truncate) 可能有效,也可能导致宇宙崩溃,具体取决于特定的实现。这也适用于以这种不受支持的模式打开的句柄的读/写操作。
模式详细信息为
:mode<ro> means "read only" :mode<wo> means "write only" :mode<rw> means "read and write" :create means the file will be created, if it does not exist :truncate means the file will be emptied, if it exists :exclusive means .open will fail if the file already exists :append means writes will be done at the end of file's current contents
尝试打开目录、写入以只读模式打开的句柄或从以只写模式打开的句柄中读取,或者对以二进制模式打开的句柄使用文本读取方法将失败或引发异常。
在6.c 语言中,可以打开路径 '-',如果以只读模式打开,这将导致 open 打开(如果 closed)$*IN 句柄;如果以只写模式打开,则打开 $*OUT 句柄。在这种情况下,所有其他模式都将导致引发异常。
从6.d 语言版本开始,不推荐使用路径 '-',它将在未来的语言版本中完全删除。
:out-buffer 控制输出缓冲,默认情况下表现得好像它是 Nil。有关详细信息,请参阅方法 out-buffer。
注意(Rakudo 2017.09 之前的版本):文件句柄在超出范围时不会刷新或关闭。虽然它们会在垃圾回收时关闭,但不能保证垃圾回收一定会运行。这意味着你应该对打开用于写入的句柄使用显式的 close,以避免数据丢失,并且建议对打开用于读取的句柄也使用显式的 close,这样你的程序就不会同时打开太多文件,从而在进一步的 open 调用时触发异常。
注意(Rakudo 2017.09 及之后的版本):打开的文件句柄会在程序退出时自动关闭,但仍然强烈建议你显式 close 打开的句柄。
在 IO::Path 中§
有关方法 open,请参阅上下文中的主要文档 in context
method open(IO::Path: *)
将路径作为文件打开;命名的选项控制模式,与 open 函数接受的选项相同。
在独立例程中§
有关子例程 open,请参阅上下文中的主要文档 in context
multi open(IO() , |args --> IO::Handle)
使用给定的 $path 创建 一个句柄,并调用 IO::Handle.open,将任何剩余参数传递给它。请注意,IO::Path 类型提供了许多用于从文件读取和写入的方法,因此在许多常见情况下,你不需要 open 文件或直接处理 IO::Handle 类型。
my = open :w, '/tmp/some-file.txt';.say: 'I ♥ writing Raku code';.close;= open '/tmp/some-file.txt';print .readchars: 4;.seek: 7, SeekFromCurrent;say .readchars: 4;.close;# OUTPUT: «I ♥ Raku»