I'm working on an CLI tool that lets you create files easily and opens it if a certain flag is true. This is the only way of opening a file in a text editor that I saw:
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)
...which I don't really understand by the way, and got the following error:
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
How do I fix this? How can I open the file with, for example, Notepad?
CodePudding user response:
You should call exec.Command
on a string whose content is a executable command path, with some arguments for this command as other parameters, like:
// 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)
Refer to document.