Golang io/ioutil.WriteFile() function example

package io/ioutil

Golang io/ioutil.WriteFile() function usage example

 package main

 import (
 "fmt"
 "io/ioutil"
 "os"
 "os/exec"
 )

 func main() {

 fileName := "./file.dat"

 str := []byte("世界你好! Hello World!")

 ioutil.WriteFile(fileName, str, os.ModeAppend)

 // somehow os.ModeAppend did not set ANY mode to the file.dat
 // and this will prevent ioutil.ReadFile from reading the
 // file.dat content

 // therefore, we need to change the mode manually
 cmd := exec.Command("chmod", "666", "file.dat")

 out, err := cmd.Output()

 if err != nil {
 fmt.Println(err)
 }

 fmt.Printf(string(out))

 readerFile, _ := ioutil.ReadFile(fileName)

 fmt.Printf("%s \n", readerFile)
 }

Output :

世界你好! Hello World!

Reference :

http://golang.org/pkg/io/ioutil/#WriteFile

Advertisement