简体   繁体   English

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

[英]How to get file mode in ruby?

I'm new to ruby file IO. 我是红宝石文件IO的新手。 I have a function that takes a File parameter, and I need to make sure that the file is in read-only mode. 我有一个带有File参数的函数,我需要确保该文件处于只读模式。

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

    #Assert that file is in read-only mode
end

Any help would be appreciated! 任何帮助,将不胜感激!

So all you need is 'make sure make sure that the file is in read-only mode', why not just set it as readonly with FileUtils.chmod . 因此,您所需要做的就是“确保文件处于只读模式”,为什么不通过FileUtils.chmod将其设置为只读。

Or if actually you just want to test if it is readonly, use File.writeable ? 或者,如果实际上您只是想测试它是否为只读,请使用File.writeable

If you don't need to raise an error, you can use reopen , I think something like: 如果您不需要引发错误,则可以使用reopen ,我认为类似:

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

I can't find a way to otherwise verify that there isn't a write stream, but here's a bit of a hack that will work. 我无法找到一种方法来验证是否没有写入流,但是这里有些技巧可以使用。 Although I don't like exception throwing being used in the expected path, you could use close_write : 尽管我不喜欢在预期的路径中使用异常抛出,但是您可以使用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

You can use file.readable? 您可以使用file.readable? , which returns true or false. ,返回true或false。

Please check this link. 请检查此链接。

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

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