Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go lang convert os.File output to String

Tags:

go

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");
}
like image 861
sudhanshu Avatar asked Oct 29 '25 11:10

sudhanshu


2 Answers

Instead of

io.Copy(os.Stdout, f)

you can do

var buf bytes.Buffer
io.Copy(&buf, f)
asString := buf.String()
like image 190
gonutz Avatar answered Oct 31 '25 09:10

gonutz


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)
like image 30
3 revsuser12258482 Avatar answered Oct 31 '25 09:10

3 revsuser12258482



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!