我正在尝试复制一些文件并计算哈希值,但对于某些文件,我得到Errno::EACCES: Permission denied @ io_fread
source = <file>
dir = <target dir>
sha_t = Digest::SHA256.file(source).hexdigest # <- Error
FileUtils.cp(source, dir)
所以我显然无权阅读该文件。所以我想我可以检查一下我是否可以阅读:
File.readable?(source)
但这会返回true。
我如何检查我是否可以读取文件?我不想begin ... rescue
更新: 我使用的是Windows和Ruby 2.1.3p242
我不想chmod
,但如果无法阅读,请跳过该文件。
答案 0 :(得分:1)
首先,如果您描述了您正在使用的操作系统和文件系统,那将非常有用。现在,我假设您正在使用* NIX和ext *文件系统。
检查文件的一种好方法是使用内置的 Pathname 类,该类适用于目录和文件。
require 'pathname'
p = Pathname.new('/mypath/myfile.rb')
p.writable?
p.readable?
我怀疑在你的情况下,问题可以通过在复制到目的地之前在目的地上设置正确的权限来解决:
Pathname.new(dir).chmod 755
FileUtils.cp(source, dir)