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

I am trying to write the output of an instruction below to a text file, but I can not find if there is a printf function that writes directly to a text file. For example, if the code below gives the results [5 1 2 4 0 3] I would like to read this in a text file for storage and preservation. Any ideas please?

The code I want to get in a text file is:

//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])
+4
source share
3 answers

You can use fmt.Fprintfalong with io.Writerwhich will represent the handle of 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()
}

Additional ways to write to a file in Go are shown here .

, panic() , ( -, , panic()).

+7

os , Fprintf

file, fileErr := os.Create("file")
if fileErr != nil {
    fmt.Println(fileErr)
    return
}
fmt.Fprintf(file, "%v\n", i)

.

+2

This example will write values ​​to a file output.txt.

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()
}
+2
source

Source: https://habr.com/ru/post/1628258/


All Articles