dongzhang5787 2015-01-29 07:19
浏览 48
已采纳

Go中的文件路径

So this is the example from Programming in Go by Mark Summerfield.

package main

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)

var britishAmerican = "british-american.txt"

func init() {
    dir, _ := filepath.Split(os.Args[0])
    britishAmerican = filepath.Join(dir, britishAmerican)
}

func main() {
    rawBytes, err := ioutil.ReadFile(britishAmerican)
    if err != nil {
        fmt.Println(err)
    }
    text := string(rawBytes)

    usForBritish := make(map[string]string)

    lines := strings.Split(text, "
")
    fmt.Println(lines)
    for _, line := range lines {
        fields := strings.Fields(line)
        if len(fields) == 2 {
            usForBritish[fields[0]] = fields[1]
        }
    }
    fmt.Println(usForBritish)
}

When I run this code with the init() func commented out, it works perfectly fine. If I leave it in I get this error:

open /var/folders/l6/rdqtyrfd303dw1cz8qvlfcvc0000gn/T/go-    build652175567/command-line-arguments/_obj/exe/british-american.txt: no     such file or directory exit status 1  

My question is, why does the init() func not grab the file from the appropriate directory?

  • 写回答

2条回答 默认 最新

  • douhan1992 2015-01-29 08:17
    关注

    You change the variable britishAmerican in the init function. Without init(), the program looks in the current directory (no path given, only the file name). With init(), it looks in the path where the executable is (os.Args[0]). And with go run main.go, the directory with the executable is not the current working directory.

    You should use go build to build the binary and then run it, or you should tell us what you want to achieve (as written by @RoninDev).


    The MCVE I've mentioned could look like this:

    package main
    
    import (
        "io/ioutil"
        "log"
        "os"
        "path/filepath"
    )
    
    var filename = "foo.txt"
    
    func init() {
        // change to true and things break
        if false {
            dir, _ := filepath.Split(os.Args[0])
            filename = filepath.Join(dir, filename)
        }
    }
    
    func main() {
           // requires a file 'foo.txt' in the current directory
        _, err := ioutil.ReadFile(filename)
        if err != nil {
            log.Fatal(err)
        }
    }
    

    It can (of course) be even shorter, but this should be enough for the others in the community to see what is going on.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析