2 回答

TA貢獻1802條經驗 獲得超5個贊
package main
import (
"fmt"
"io"
"log"
"os"
)
func main() {
file, err := os.Create("myfile")
if err != nil {
log.Fatal(err)
}
mw := io.MultiWriter(os.Stdout, file)
fmt.Fprintln(mw, "This line will be written to stdout and also to a file")
}

TA貢獻2080條經驗 獲得超4個贊
使用fmt.Fprint()要保存到文件的調用的方法。還有fmt.Fprintf()和fmt.Fprintln()。
這些函數將目標io.Writer作為第一個參數,您可以將文件 ( *os.File) 傳遞給該目標。
例如:
f, err := os.Open("data.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
fmt.Println("This goes to standard output.")
fmt.Fprintln(f, "And this goes to the file")
fmt.Fprintf(f, "Also to file, with some formatting. Time: %v, line: %d\n",
time.Now(), 2)
如果您希望所有fmt.PrintXX()調用都轉到您無法控制的文件(例如,您無法更改它們,fmt.FprintXX()因為它們是另一個庫的一部分),您可以os.Stdout臨時更改,因此所有進一步fmt.PrintXX()的調用都將寫入您設置的輸出,例如:
// Temporarily set your file as the standard output (and save the old)
old, os.Stdout = os.Stdout, f
// Now all fmt.PrintXX() calls output to f
somelib.DoSomething()
// Restore original standard output
os.Stdout = old
- 2 回答
- 0 關注
- 183 瀏覽
添加回答
舉報