繁体   English   中英

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

[英]How to get file mode in ruby?

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

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

    #Assert that file is in read-only mode
end

任何帮助,将不胜感激!

因此,您所需要做的就是“确保文件处于只读模式”,为什么不通过FileUtils.chmod将其设置为只读。

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

如果您不需要引发错误,则可以使用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

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

请检查此链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM