douluan5444 2018-06-03 19:05
浏览 56
已采纳

通过另一个文件导入时,仅使用ioutils ReadDir扫描当前目录中的文件

I'm having an issue with ioutils.ReadDir, for some reason it's scanning for all files in the project root instead of in the current directory only.

./main.go

import (
    "myfolder/myfile"
)

func main() {
    myfile.MyFunction()
}

./myfolder/myfile.go

package myfile

func MyFunction() {
    files, err := ioutil.ReadDir(".")
    if err != nil {
        log.Fatal(err)
    }

    for _, f := range files {
        fi, err := os.Stat(f.Name())
        if err != nil {
            log.Fatal(err)
            return
        }

        switch mode := fi.Mode(); {
        case mode.IsDir():
            fmt.Printf("%#s  is a folder
", f.Name())
        case mode.IsRegular():
            fmt.Printf("%#s is a file
", f.Name())
        }
    }
}

I'm not really sure why it is behaving like this, I'm new to Go. My guess is because it's being imported through main.go. How can I make it only search for folders and files in ./myfolder?

  • 写回答

1条回答 默认 最新

  • doupi3874 2018-06-03 19:20
    关注

    The current directory is not the directory of the source files, but rather the current directory of whoever executes the program.

    If you're executing the program from a shell (be it bash or the Windows command line), the program inherits the current directory from your shell.

    You must change the current directory with cd myfolder before executing the program or call os.Chdir("myfolder") in your Go source file. (os.Chdir doesn't affect your shell's current directory)

    If you want to list a directory recursively, you must walk it. See filepath.Walk.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大