gpt4 book ai didi

戈朗 : Walk Directory Tree and Process Files -- err = 'no such file or directory

转载 作者:IT王子 更新时间:2023-10-29 01:37:10 25 4
gpt4 key购买 nike

我正在编写一个例程来遍历目录树并为我找到的每个文件创建数字签名(加盐哈希)。在测试它时,我得到了这种奇怪的行为——如果我给程序一个目录“上方”的根路径,程序可以遍历树并打印出文件名,但是如果我尝试打开文件来读取它的字节,我在例程找到的文件上收到错误消息“没有这样的文件或目录” - 不确定这里给出的是什么。 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
}

最佳答案

尝试在 walkFn 中记录 pathfullPath 的值。

walkFn 中使用 filepath.Abs​​() 不会给出您想要的结果:它正在解析相对于当前工作目录的文件名,而不是原始的 dirPath .

一种选择是在 doHashWalk 中预先将目标目录解析为绝对路径:

func doHashWalk(dirPath string) {
fullPath, err := filepath.Abs(dirPath)

if err != nil {
log.Println("path error:", err)

return
}

err = filepath.Walk(fullPath, walkFn)

// check err here
}

随着这一变化,walkFn 回调将始终接收一个完全限定的 path 参数;无需再次调用 filepath.Abs​​():

func walkFn(path string, fi os.FileInfo, err error) (e error) {
// ...

bytes, err := ioutil.ReadFile(path)

// ...
}

如果您的应用程序查看每个文件相对于原始 dirPath 根目录的路径很重要,您可以通过闭包将该路径隐藏到 walkFn 回调中:

func doHashWalk(dirPath string) error {

fullPath, err := filepath.Abs(dirPath)

if err != nil {
return err
}

callback := func(path string, fi os.FileInfo, err error) error {
return hashFile(fullPath, path, fi, err)
}

return filepath.Walk(fullPath, callback)
}

func hashFile(root string, path string, fi os.FileInfo, err error) error {
if fi.IsDir() {
return nil
}

rel, err := filepath.Rel(root, path)

if err != nil {
return err
}

log.Println("hash rel:", rel, "abs:", path)

return nil
}

关于戈朗 : Walk Directory Tree and Process Files -- err = 'no such file or directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20382624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com