Golang检查文件扩展名不起作用

huangapple go评论87阅读模式
英文:

Golang Checking file extension not working

问题

我想从控制台获取一个文件路径,并检查该文件是否为vm文件。
我写了这段代码:

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Println("请输入vm文件的路径:")
    path, _ := reader.ReadString('\n')
    if filepath.Ext(path) != ".vm" {
        fmt.Println("错误!文件必须是vm文件")
    }
}

但是它没有起作用。我刚开始学习Go语言,如果这是一个基本错误,请原谅。

英文:

I want to get a file path from the console and check if the file is a vm file.
I wrote this code:

func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter the path of the vm file:")
path, _ := reader.ReadString('\n')
if filepath.Ext(path) != ".vm" {
	fmt.Println("Error! file must be vm file")
}

but it's not working. I just started learn Go So please accept my apologies if this is a basic mistake.

答案1

得分: 18

检查文件扩展名的代码:

path := "/media/godfather.mp4"

fileExtension := filepath.Ext(path)

if fileExtension != ".mp4" {
    panic("文件扩展名不等于 .mp4")
}
英文:

For checking file extension:

path := "/media/godfather.mp4"

fileExtension := filepath.Ext(path)

if fileExtension != ".mp4" {
    panic("File extension ins't equal to .mp4")
}

答案2

得分: 8

path, _ := reader.ReadString('\n') 也会返回换行符。所以你正在将 ".vm\n" 与 ".vm" 进行比较。

你应该从路径中使用 strings.TrimSpace(path) 去除空格,然后进行比较 if filepath.Ext(strings.TrimSpace(path)) != ".vm" {

英文:

The path, _ := reader.ReadString('\n') also returns the newline. So your comparing ".vm\n" with ".vm".

you should trimspace from the path if filepath.Ext(strings.TrimSpace(path)) != ".vm" {

huangapple
  • 本文由 发表于 2016年3月13日 22:02:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/35971181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定