doutu6658 2016-04-08 22:09
浏览 137
已采纳

执行:将文件指针传递给其他函数?

If i have created a file in my main() function:

output, err := os.Create("D:\\output.txt")

And i want everything that another function in the program prints, to be put in that file using:

output.WriteString(str)

How could i pass a pointer to that file so that function could write to it? Also, is there any other way i should use to write a string to a file, or WriteString is succicient?

Thanks!

  • 写回答

3条回答 默认 最新

  • douyong1885 2016-04-08 22:15
    关注

    Have your function take a pointer as a parameter using the * type modifier, and just pass your file object as-is since os.Create already returns a pointer:

    func WriteStringToFile(f *os.File) {
        n, err := f.WriteString("foobar")
    }
    
    // ..
    
    output, err := os.Create("D:\\output.txt")
    WriteStringToFile(output)
    

    Also, please note that it is good practice not to ignore errors.

    To write strings into a file can be done in a few different ways, especially if you want to avoid using the os.File object directly, and only use the io.Writer interface. For example:

    fmt.Fprint(output, "foo bar")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog