golang如何读取文件名中包含空格的文件

环境:

win8.1 x64, go1.3 x64

程序调用方式:

./test.exe -f aaa.txt
./test.exe -f aa a.txt #这种情况报错
./test.exe -f "aa a.txt" #这种情况也报错
./test.exe -f aa\ a.txt #这种情况也是报错

问题描述:

只要是当前文件中含有空格程序就报错,上面几种调用方式报错都一样,错误如下:

panic: open file_name: The system cannot find the file specified.

goroutine 16 [running]:
runtime.panic(0x4d6740, 0xc082005e00)
        c:/go/src/pkg/runtime/panic.c:279 +0x11f
main.is_file(0xc0820001a8, 0x2)
        D:/www/scripts/go/test/test.go:24 +0x88
main.main()
        D:/www/scripts/go/test/test.go:15 +0x9a

goroutine 19 [finalizer wait]:
runtime.park(0x414e60, 0x594060, 0x592aa9)
        c:/go/src/pkg/runtime/proc.c:1369 +0xac
runtime.parkunlock(0x594060, 0x592aa9)
        c:/go/src/pkg/runtime/proc.c:1385 +0x42
runfinq()
        c:/go/src/pkg/runtime/mgc0.c:2644 +0xdd
runtime.goexit()
        c:/go/src/pkg/runtime/proc.c:1445

程序内容:

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    file_name := flag.String("f", "", "文件名")

    flag.Parse()
    if *file_name != "" {
        is_file(*file_name)
    } else {
        fmt.Printf("test\n")
    }
}

func is_file(file_name string) {
    file, err := os.Open(file_name)
    if err != nil {
        panic(err)
    }
    defer file.Close()

    input, _ := ioutil.ReadAll(file)
    fmt.Println(input)
}

谢谢


第一次修改 2014.07.29 10:12

阅读 11.6k
3 个回答

这不是go的问题,是找不到文件。
把空格转义一下。

./test.exe -f aa\ a.txt
新手上路,请多包涵

亲测,转义后有效 (Ubuntu)
$ ./a -f a\ a.txt
[97 98 99 100 101 102 103 10]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题