5

[Golang] Write String to File

 2 years ago
source link: http://siongui.github.io/2016/04/05/go-write-string-to-file/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Golang] Write String to File

Updated: March 01, 2017

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

osiocopy.go | repository | view raw

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

[5]Write files using Go : golang


Author: Siong-Ui Te Category: Go

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK