I'm trying to write the output of the statement below into a text file but I can't seem to find out if there is a printf function that writes directly to a text file. For example if the code below produces the results [5 1 2 4 0 3] I would want to read this into a text file for storage and persistence. Any ideas please?
The code I want to goto the text file:
//choose random number for recipe
r := rand.New(rand.NewSource(time.Now().UnixNano()))
i := r.Perm(5)
fmt.Printf("%v\n", i)
fmt.Printf("%d\n", i[0])
fmt.Printf("%d\n", i[1])
Go write to file with ioutil.The outil. WriteFile writes data to the specified file. This is a higher-level convenience function. The opening and closing of the file is handled for us.
Golang offers a vast inbuilt library that can be used to perform read and write operations on files. In order to read from files on the local system, the io/ioutil module is put to use. The io/ioutil module is also used to write content to the file.
WriteFile() to write this byte array to a file.
The simplest way of reading a text or binary file in Go is to use the ReadFile() function from the os package. This function reads the entire content of the file into a byte slice, so you should be careful when trying to read a large file - in this case, you should read the file line by line or in chunks.
You can use fmt.Fprintf
together with an io.Writer
, which would represent a handle to your file.
Here is a simple example:
func check(err error) {
if err != nil {
panic(err)
}
}
func main() {
f, err := os.Create("/tmp/yourfile")
check(err)
defer f.Close()
w := bufio.NewWriter(f)
//choose random number for recipe
r := rand.New(rand.NewSource(time.Now().UnixNano()))
i := r.Perm(5)
_, err = fmt.Fprintf(w, "%v\n", i)
check(err)
_, err = fmt.Fprintf(w, "%d\n", i[0])
check(err)
_, err = fmt.Fprintf(w, "%d\n", i[1])
check(err)
w.Flush()
}
More ways of writing to file in Go are shown here.
Note that I have used panic()
here just for the sake of brevity, in the real life scenario you should handle errors appropriately (which in most cases means something other than exiting the program, what panic()
does).
This example will write the values into the output.txt
file.
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
)
func main() {
file, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("File does not exists or cannot be created")
os.Exit(1)
}
defer file.Close()
w := bufio.NewWriter(file)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
i := r.Perm(5)
fmt.Fprintf(w, "%v\n", i)
w.Flush()
}
Use os
package to create file and then pass it to Fprintf
file, fileErr := os.Create("file")
if fileErr != nil {
fmt.Println(fileErr)
return
}
fmt.Fprintf(file, "%v\n", i)
This should write to file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With