如何在Ruby中获取文件模式?

时间:2018-10-13 21:25:08

标签: ruby file io

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

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

    #Assert that file is in read-only mode
end

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:2)

因此,您所需要做的只是'确保文件处于只读模式',为什么不直接使用FileUtils.chmod将其设置为只读。

还是实际上您只是想测试它是否为只读,请使用File.writeable

答案 1 :(得分:2)

如果您不需要提出错误,可以使用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 :(得分:1)

您可以使用file.readable?,它返回true或false。

请检查this link.