亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Golang 的文本文件中捕獲 fmt.Print 輸出

如何在 Golang 的文本文件中捕獲 fmt.Print 輸出

Go
呼如林 2022-04-20 16:54:21
我想將某些fmt.Print語句保存到 .txt 文件中。我不想存儲所有打印語句。我可以這樣做嗎?
查看完整描述

2 回答

?
12345678_0001

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")

}


查看完整回答
反對 回復 2022-04-20
?
犯罪嫌疑人X

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


查看完整回答
反對 回復 2022-04-20
  • 2 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號