簡體   English   中英

如何在 Go 中使用文本編輯器打開文件?

[英]How do I open a file with a text editor in Go?

我正在開發一個 CLI 工具,它可以讓您輕松創建文件並在某個標志為真時打開它。 這是我看到的在文本編輯器中打開文件的唯一方法:

    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)

請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM