Consider a Go program that runs another exe file:
command := exec.Command("C:\\myapplication.exe")
if err := command.Run(); err != nil {
}
And consider that myapplication.exe contains below code segment:
os.Create("generatedfile.txt")
The problem is that the generatedfile.txt is created in the directory of the parent process and not in the directory of the child process (C:\). What should be done to transfer control to the child process in such a way that the file is created in the child process's directory without changing the string inside os.Create (i.e. generatedfile.txt)?
The exec Cmd.Dir documentation says:
Dir specifies the working directory of the command. If Dir is the empty string, Run runs the command in the calling process's current directory.
The application does not set the command.Dir
, therefore the child process runs in the calling process's current directory.
To fix the problem, set command.Dir
to the directory where you want to run the child process.
command := exec.Command("C:\\myapplication.exe")
command.Dir = "C:\\some\\directory"
if err := command.Run(); err != nil {
}
f, err := os.Create("generatedfile.txt")
// file is created in C:\some\directory\generatedfile.txt