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!
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")
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()
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.