Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the output of this statement into a file in Golang

Tags:

file

io

go

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])
like image 763
Tbalz Avatar asked Feb 11 '16 07:02

Tbalz


People also ask

How do you write data into a file in Go?

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.

How do I read and write files in Golang?

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.

Which function is used to write an array of bytes into a file in Golang?

WriteFile() to write this byte array to a file.

How do I view the contents of a file in Golang?

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.


3 Answers

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

like image 125
syntagma Avatar answered Oct 19 '22 05:10

syntagma


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()
}
like image 5
Endre Simo Avatar answered Oct 19 '22 03:10

Endre Simo


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.

like image 4
sfault Avatar answered Oct 19 '22 05:10

sfault