sudhanshu
sudhanshu

Reputation: 453

Go lang convert os.File output to String

How to convert Os.File output into string instead of printing to shell. I am using github.com/kr/pty library to execute commands.

How can convert the output to sting instead of printing to console.

f belongs to Os.File in below example. How to convert it to string.

package main

import (
    "github.com/kr/pty"
    "io"
    "os"
    "os/exec"
)

func run_command(cmd string){
    c := exec.Command("/bin/sh", "-c", cmd)
    f, err := pty.Start(c)
    if err != nil {
        panic(err)
    }
    io.Copy(os.Stdout, f)
}

func main() {
    run_command("ls -lrt");
}

Upvotes: 4

Views: 3716

Answers (2)

gonutz
gonutz

Reputation: 5582

Instead of

io.Copy(os.Stdout, f)

you can do

var buf bytes.Buffer
io.Copy(&buf, f)
asString := buf.String()

Upvotes: 4

user12258482
user12258482

Reputation:

An *os.File is an io.Reader. There are a few ways to convert the contents of an io.Reader to a string using the standard library.

The strings.Builder approach might perform better than the other approaches because strings.Builder does not allocate memory when converting the accumulated bytes to a string. This performance benefit is probably negligible in the context of the question.

Otherwise, the choice of approach is a matter of taste and opinion.

strings.Builder

var buf strings.Builder
_, err := io.Copy(&buf, f)
if err != nil {
    // handle error
}
s := buf.String()

bytes.Buffer

var buf bytes.Buffer
_, err := buf.ReadFrom(f)
if err != nil {
    // handle error
}
s := buf.String()

ioutil.ReadAll

p, err := ioutil.ReadAll(f)
if err != nil {
     // handle error
}
s := string(p)

Upvotes: 2

Related Questions