犯罪嫌疑人X
使用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 fsomelib.DoSomething()// Restore original standard outputos.Stdout = old