[Golang] Write String to File


Golang - write string to file via os Create method and io Copy method.

osiocopy.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package write

import (
	"io"
	"os"
	"strings"
)

func WriteStringToFile(filepath, s string) error {
	fo, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer fo.Close()

	_, err = io.Copy(fo, strings.NewReader(s))
	if err != nil {
		return err
	}

	return nil
}

Usage:

if err := WriteStringToFile("good.txt", "% in string\n"); err != nil {
      panic(err)
}

Output (good.txt):

% in string

Caveat: Do not use fmt.Fprintf to write string to file. See [4] for more details.


Tested on: Ubuntu Linux 16.10, Go 1.8.


References:

[1]os - The Go Programming Language
[2]io - The Go Programming Language
[3]fmt - The Go Programming Language
[4][Golang] Caveat of fmt.Fprintf Use
[5]Write files using Go : golang