开发者社区> 问答> 正文

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

环境:

win8.1 x64, go1.3 x64

程序调用方式:

问题描述:

只要是当前文件中含有空格程序就报错,错误如下:

The system cannot find the file specified. goroutine 16 [running]: runtime.panic(0x4d6740, 0xc082005d70) c:/go/src/pkg/runtime/panic.c:279 +0x11f main.is_file(0xc082000170, 0x7) D:/www/scripts/go/test/test.go:24 +0x8b main.main() D:/www/scripts/go/test/test.go:15 +0x9a goroutine 17 [runnable]: runtime.MHeap_Scavenger() c:/go/src/pkg/runtime/mheap.c:507 runtime.goexit() c:/go/src/pkg/runtime/proc.c:1445 goroutine 18 [runnable]: bgsweep() c:/go/src/pkg/runtime/mgc0.c:1976 runtime.goexit() c:/go/src/pkg/runtime/proc.c:1445 goroutine 19 [runnable]: runfinq() c:/go/src/pkg/runtime/mgc0.c:2606 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)
}



谢谢...


展开
收起
爱吃鱼的程序员 2020-06-15 19:43:46 1546 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    <spanstyle="font-family:Consolas,'BitstreamVeraSansMono','CourierNew',Courier,monospace;font-size:14px;line-height:15.399999618530273px;background-color:#FFFFFF;">flag.String在读取文件名时,如果你在文件名上加上了双引号,那么,不管文件名中是否存在空格,都会当成一个整体读取,不会出现文件名有空格时出错的问题是我理解错了还怎么着,是这样么-f"$(FileName)",这样也不行,直接命令行调用test.exe-f"something.txt"这样也不行."filename"不明白,什么意思能具体说下么.谢谢

    2020-06-15 19:44:04
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
阿里开发者手册-Golang专题 立即下载
Golang 微服务在腾讯游戏用户运营领域的探索及实践 立即下载
低代码开发师(初级)实战教程 立即下载

相关镜像