PracticeDev/study_go/stdout/stdout-to-file/main.go

43 lines
720 B
Go
Raw Normal View History

2022-12-20 17:31:11 +08:00
package main
import (
"fmt"
"os"
)
var tmpFile = "./tmp.txt"
func tmpPrint() {
fmt.Println("output")
}
func main() {
old := os.Stdout // keep backup of the real stdout
w, err := os.OpenFile(tmpFile, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err)
return
}
defer w.Close()
os.Stdout = w
tmpPrint()
//outC := make(chan string)
// copy the output in a separate goroutine so printing can't block indefinitely
//go func() {
// var buf bytes.Buffer
// io.Copy(&buf, r)
// outC <- buf.String()
//}()
// back to normal state
//w.Close()
os.Stdout = old // restoring the real stdout
//out := <-outC
// reading our temp stdout
fmt.Println("previous output:")
//fmt.Print(out)
}