登录
首页 >  Golang >  Go问答

在 Go 中如何实现打开文件并使用文本编辑器编辑?

来源:stackoverflow

时间:2024-02-27 16:36:24 250浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《在 Go 中如何实现打开文件并使用文本编辑器编辑?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我正在开发一个 cli 工具,它可以让您轻松创建文件并在某个标志为 true 时打开它。这是我看到的在文本编辑器中打开文件的唯一方法:

    cmd := exec.command(file)
    cmd.stdin = os.stdin
    cmd.stdout = os.stdout
    cmd.stderr = os.stderr
    err = cmd.start()
    if err != nil {
        fmt.printf("start failed: %s", err)
    }
    fmt.printf("waiting for command to finish.\n")
    err = cmd.wait()
    fmt.printf("command finished with error: %v\n", err)

...顺便说一句,我不太明白,并收到以下错误:

Start failed: fork/exec H:/code/txt_projects/hello6.txt: %1 is not a valid Win32 application.Waiting for command to finish.
Command finished with error: exec: not started

我该如何解决这个问题?如何使用记事本等打开该文件?


正确答案


您应该在内容为可执行命令路径的字符串上调用 exec.command,并使用该命令的一些参数作为其他参数,例如:

    // shortcut for command in ENV PATH
    //exepath := "notepad"
    exepath := "C:\\Windows\\system32\\notepad.exe"
    file := "H:\\code\\txt_projects\\hello6.txt"
    cmd := exec.Command(exepath, file)

参考document

今天关于《在 Go 中如何实现打开文件并使用文本编辑器编辑?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>