Ruby中的文件打开模式

55
我是Ruby的新手程序员。请问有人可以给出在Ruby中使用r+、w+、a+模式打开文件的例子吗?它们与r、w、a模式有什么区别?
请解释并提供示例。
1个回答

116
文件打开模式并不是特定于 Ruby 的 - 它们是 IEEE Std 1003.1(Single UNIX Specification)的一部分。您可以在此处阅读更多信息:

http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

r or rb
    Open file for reading.

w or wb
    Truncate to zero length or create file for writing.

a or ab
    Append; open or create file for writing at end-of-file.

r+ or rb+ or r+b
    Open file for update (reading and writing).

w+ or wb+ or w+b
    Truncate to zero length or create file for update.

a+ or ab+ or a+b
    Append; open or create file for update, writing at end-of-file.

任何带有字母'b'的模式表示二进制文件。如果'b'不存在,则为“纯文本”文件。
“打开”和“以更新方式打开”的区别如下:
当使用更新模式(将'+'作为模式参数中的第二个或第三个字符)打开文件时,可以在关联的流上执行输入和输出。但是,应用程序必须确保,在进行输出而没有中间调用fflush()或文件定位函数(fseek()、fsetpos()或rewind())的情况下,不直接跟随输入;并且在进行输入而没有中间调用文件定位函数的情况下,不直接跟随输出,除非输入操作遇到文件结束。

1
对于那些对快速示例感兴趣的人,以下演示了如何将内容追加到文件中:echo "foobar" > some_file && ruby -e 'File.open("some_file", "a") { |f| f.puts "catdog" }' - mbigras

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接