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 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)