ruby - 如何在ruby中获取文件模式?

标签 ruby file io

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

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

    #Assert that file is in read-only mode
end

如有任何帮助,我们将不胜感激!

最佳答案

如果你不需要报错,你可以使用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

关于ruby - 如何在ruby中获取文件模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797474/

相关文章:

java - 文件编写器覆盖文件而不是附加到末尾的问题

c - 从文件中读取双二进制数据

c - 在我的 C 程序中遇到结构和数组问题

flutter - File.writeAsBytes 的 'flush' 参数在 Dart.io 中有什么作用?

java - Java根据部分文件名检查文件是否存在

java - 如果第一个字母是大写则删除单词

ruby-on-rails - 跨多个 Rails 应用程序重用 Ruby 代码

ruby - 确定给定的 IP 地址是否在网络数组中

ruby - 'for' 标签从未关闭/如果 elsif else 在液体逻辑中包含页面?

ruby - puts 输出中的转义换行符