dougan6402 2018-01-09 17:09
浏览 236
已采纳

转到父目录

I've some command line program which I need to read files from parent folder, I mean

-parentDir
 -- myproject
 --- cmd
 ----main.go 

 --otherdir
  -file.json 

As you can see otherdir is like sibling to myproject and I need from my main.go read the file.json

what I've tried is like following

func visit(path string, f os.FileInfo, err error) error {
  fmt.Printf("Visited: %s
", path)
  return nil
} 


func main() {
  flag.Parse()
  root := flag.Arg(0)
  err := filepath.Walk(root, visit)
  fmt.Printf("filepath.Walk() returned %v
", err)
}

I've also try to provide args(-1) which doesnt help... Any idea how from command line program I can read some files that on level up from my executable ?

I've also tried with

import "github.com/mitchellh/go-homedir"


func Path(path string) (error, string) {
    home, err := homedir.Dir()
   }

this give the root directory which doesnt help either...

  • 写回答

1条回答 默认 最新

  • dsgft1486 2018-01-09 17:12
    关注

    It doesn't matter where the binary is, it matters what the working directory is (the directory you're in when you execute the program). All relative paths will be relative to the current working directory. So, if you're executing from myproject, you'd use something like ../ as the root path to Walk.

    That said, I would highly recommend you make the path configurable, rather than assuming the binary will always be executed from some particular location within the source tree.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?