Golang: write [] int to file

I have some data in p []int, I want to save / load it to / from a file. Should I convert this fragment to []byteand use (if yes, how?)

func (f *File) Read(b []byte) (n int, err Error)
func (f *File) Write(b []byte) (n int, err error)

or is there another way to save []intto a file?

I read this. How to read / write from / to a file using golang? and it didn’t help.

+4
source share
2 answers

If sharing files (between languages ​​other than go) or reading it as a stream does not matter to you, just use an encoder and decoder gob.

http://golang.org/pkg/encoding/gob/

, , . :

p := []int{1,2,3,4}

encoder := gob.NewEncoder(myFileWriter)
err = encoder.Encode(p)
if err != nil {
    panic(err)
}

:

decoder := gob.NewDecoder(myFileReader)
p := []int{}

err = decoder.Decode(&p)
if err != nil {
         panic(err)
}

, , JSON XML, ( ).

+10

file.WriteString(fmt.Sprintln(p))

:

    /*path of the file test.txt : you have to change it*/
var path = "/Users/Pippo/workspace/Go/src/......./test.txt"

func main() {

    p := []int{1, 2, 3, 4, 5, 8, 99}
    fmt.Println(p)
    createFile()
    writeFile(p)

}

/*create file*/
func createFile() {

    // detect if file exists
    var _, err = os.Stat(path)

    // create file if not exists
    if os.IsNotExist(err) {
        var file, err = os.Create(path)
        if isError(err) {
            return
        }
        defer file.Close()
    }

    fmt.Println("==> done creating file", path)
}



/* print errors*/
func isError(err error) bool {
    if err != nil {
        fmt.Println(err.Error())
    }

    return (err != nil)
}

/*writeFile write the data into file*/
func writeFile(p []int) {

    // open file using READ & WRITE permission
    var file, err = os.OpenFile(path, os.O_RDWR, 0644)

    if isError(err) {
        return
    }
    defer file.Close()

    // write into file
    _, err = file.WriteString(fmt.Sprintln(p))
    if isError(err) {
        return
    }

    // save changes
    err = file.Sync()
    if isError(err) {
        return
    }

    fmt.Println("==> done writing to file")
}
+1

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


All Articles