【问题标题】:File opening mode in RubyRuby 中的文件打开模式
【发布时间】:2011-08-16 22:00:23
【问题描述】:

我是 Ruby 的新程序员。有人可以举一个关于在 Ruby 中使用 r+、w+、a+ 模式打开文件的例子吗?它们和r,w,a有什么区别?

请解释一下,并举例说明。

【问题讨论】:

    标签: ruby file posix


    【解决方案1】:

    文件打开模式并不是真正特定于 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”不存在,则为“纯文本”文件。

    'open'和'open for update'的区别表示为:

    当以更新模式(模式参数中的第二个或第三个字符'+')打开文件时,可以在关联的流上执行输入和输出。但是,应用程序应确保在没有对 fflush() 或文件定位函数(fseek()、fsetpos() 或 rewind())的介入调用的情况下,输出不直接跟在输入之后,并且输入不直接跟在输入之后输出没有对文件定位函数的干预调用,除非输入操作遇到文件结尾。

    【讨论】:

    • 对于对快速示例感兴趣的人,以下演示了附加到文件:echo "foobar" > some_file && ruby -e 'File.open("some_file", "a") { |f| f.puts "catdog" }'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    相关资源
    最近更新 更多