17

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])
syntagma
  • 23,346
  • 16
  • 78
  • 134
Tbalz
  • 662
  • 1
  • 7
  • 24
  • Users who are watching this questing may be interested in **How to write log to file in Go** https://stackoverflow.com/questions/19965795/how-to-write-log-to-file – Arun Apr 12 '20 at 00:26

3 Answers3

27

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).

syntagma
  • 23,346
  • 16
  • 78
  • 134
5

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()
}
Endre Simo
  • 11,330
  • 2
  • 40
  • 49
4

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.

sfault
  • 693
  • 5
  • 9