n00py
n00py

Reputation: 19

How can I run the dir command with golang?

Here is my code:

package main

import (
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func runCommand(command string) io.Writer{
    cmdName := "cmd.exe"
    cmdArgs := []string{"/c", command}
    fmt.Println("Running command: " + command)
    cmd := exec.Command(cmdName, cmdArgs...)
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    cmd.Run()
    return cmd.Stdout

}
func main(){
    fmt.Println(runCommand("dir"))  // Prints the output of dir for the current directory
    fmt.Println(runCommand("dir C:\\")) // Prints nothing
    fmt.Println(runCommand("dir C:\\Users\\"))  //Prints the output of dir for the users directory
    fmt.Println(runCommand("dir C:\\..\\"))  // Prints the output of dir for the C drive (What I want)
}

I'm expecting that when I execute dir C:\ That I would get the output as if I had ran in in a windows command prompt. Instead I get nothing. Intestingly, any other path when running dir works just fine. I can even see C:\ If I instead execute C:\..\ Why is this? I don't understand why this happens, and every other windows command I have given it works fine.

Upvotes: 1

Views: 1158

Answers (1)

cd1
cd1

Reputation: 16534

First of all, never ignore errors. The call to cmd.Run() returns an error, you should always check it:

if err := cmd.Run(); err != nil {
    fmt.Printf(os.Stderr, "%v", err)
}

Try that and you might see why your command is failing.

Without knowing the error, it's hard to help fixing your problem, but I'd guess you need to split the string command into several fields and append them to cmdArgs. When running runCommand("dir C:\\"), your cmdArgs is actually []string{"/c", "dir C:\\"), I think it should be []string{"/c", "dir", "C:\\"}. Take a look at the function strings.Split(string, string), it might help you. But that's just a guess, we need to know the exact error message you're having for a proper solution :)

Upvotes: 1

Related Questions