【问题标题】:How to get file mode in ruby?如何在 ruby​​ 中获取文件模式?
【发布时间】:2019-03-18 17:52:05
【问题描述】:

我是 ruby​​ 文件 IO 的新手。我有一个带有File 参数的函数,我需要确保文件处于只读模式。

def myfunction(file)
    raise ArgumentError.new() unless file.kind_of?(File)

    #Assert that file is in read-only mode
end

任何帮助将不胜感激!

【问题讨论】:

  • 也许你想要file.kind_of?(File)以防file.class == IO。见Object#kind_of?。您可以使用测试file.readpartial(0) rescue false 排除只写,如果允许读取,它将返回一个空字符串(真实);否则返回false。不完全是你想要的,而且非常hackish。我不确定你为什么要测试这个,顺便说一句。

标签: ruby file io


【解决方案1】:

如果你不需要引发错误,你可以使用reopen,我认为是这样的:

file = file.reopen(file.path, "r")

我找不到其他方法来验证不存在写入流,但这里有一些可行的方法。虽然我不喜欢在预期路径中使用异常抛出,但您可以使用close_write

begin
  file.close_write
  # you could actually raise an exception here if you want
  # since getting here means the file was originally opened for writing
rescue IOError
  # This error will be raised if the file was not opened for
  # writing, so this is actually the path we want
end

【讨论】:

    【解决方案2】:

    所以您只需要“确保文件处于只读模式”,为什么不使用FileUtils.chmod 将其设置为只读。

    或者如果你实际上只是想测试它是否是只读的,使用File.writeable

    【讨论】:

    • 该文件可能能够在磁盘上具有写入权限,而 ruby​​ 脚本/应用程序可能想要验证打开的文件处理程序是否仅处于读取模式(不清楚原因,但这是我对问题的解读)。因此,我认为我们不想对这个问题进行 chmod 甚至根据文件系统权限做出决定。
    【解决方案3】:

    您可以使用file.readable?,它返回真或假。

    请查看this link.

    【讨论】:

    • 请注意readable?writable? 方法是指磁盘权限,而不是ruby 文件I/O。 f = File.open("tmp/readable", "r"); File.readable?(f.path) 返回true 用于磁盘上对当前用户具有权限的现有文件。
    猜你喜欢
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多