英文:
How to pass a file pointer to a different function
问题
如果我在我的main()
函数中创建了一个文件:
output, err := os.Create("D:\\output.txt")
并且我希望程序中的另一个函数打印的所有内容都被写入到该文件中:
output.WriteString(str)
我该如何传递一个指向该文件的指针,以便该函数可以向其写入内容?
此外,是否还有其他方法可以将字符串写入文件,或者使用WriteString
就足够了?
英文:
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?
答案1
得分: 4
请注意,以下是翻译好的内容:
让你的函数使用*
类型修饰符将指针作为参数,并且直接传递文件对象,因为os.Create
已经返回了一个指针:
func WriteStringToFile(f *os.File) {
n, err := f.WriteString("foobar")
}
// ..
output, err := os.Create("D:\\output.txt")
WriteStringToFile(output)
另外,请注意最好不要忽略错误。
要将字符串写入文件可以使用几种不同的方法,特别是如果你想避免直接使用os.File
对象,只使用io.Writer
接口。例如:
fmt.Fprint(output, "foo bar")
英文:
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
得分: 2
简单地定义一个函数,该函数可以接受*File
指针作为参数:
func Write(output *os.File) {
(...)
}
Write(&output) // 调用函数。
另外,你可能希望确保在最后关闭文件:
defer output.Close()
英文:
Simply define a function that can take *File
pointer as argument:
func Write(output *os.File) {
(...)
}
Write(&output) //call function.
}
Also you may want to ensure that file is closed in the end using:
defer output.Close()
答案3
得分: 2
使用诸如io.Writer
之类的接口是正确的方法。在Go语言中,许多类型通过具有Write
方法来实现io.Writer
接口。os.File
就是其中之一。
英文:
Using an interface such as io.Writer
is the way to go. Many types in Go fulfill the io.Writer
just by having a Write
method. os.File
is one of those types.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论