英文:
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" {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论