我正在编写一个程序来遍历目录树并为找到的每个文件创建数字签名(加盐哈希)。在测试过程中,我遇到了奇怪的行为——如果我给程序一个位于目录上方的根路径,程序可以遍历目录树并打印出文件名,但是如果我尝试打开文件以读取它的字节,则会收到“没有这样的文件或目录”的错误消息,这个错误发生在例程找到的文件上。不确定这是什么原因造成的。Walk()例程如何“看到”文件,而ioutil.ReadFile()则无法找到它?
示例代码:
示例代码:
// start with path higher up the tree, say $HOME
func doHashWalk(dirPath string) {
err := filepath.Walk(dirPath, walkFn)
// Check err here
}
func walkFn(path string, fi os.FileInfo, err error) (e error) {
if !fi.IsDir() {
// if the first character is a ".", then skip it as it's a hidden file
if strings.HasPrefix(fi.Name(), ".") {
return nil
}
// read in the file bytes -> get the absolute path
fullPath, err := filepath.Abs(fi.Name())
if err != nil {
log.Printf("Abs Err: %s", err)
}
// THIS ALWAYS FAILED WITH ERROR
bytes, err := ioutil.ReadFile(fullPath) // <-- (fi.Name() also doesn't work)
if err != nil {
log.Printf("Err: %s, Bytes: %d", err, len(bytes))
}
// create the salted hash
...
}
return nil
}
fi.Name()
只提供文件名,而不是路径。使用path
进行绝对调用,其中包含文件的目录名和基本名称。 - DavidGamba