GO言語Fprintシリーズを使用してファイルに書き込む
2171 ワード
まず、Fpシリーズについて説明します.
Fprintf()はformat形式の説明子に基づいてコンテンツをフォーマットしてファイルに書き込み、コンテンツが書き込まれたバイトとエラーであることを返します.
Fprint()とFprintln()は、デフォルトのフォーマットでコンテンツをファイルに書き込みます.違いはprint型とprintln型と一致する.
Fprintlnを例に挙げると、他の類似点があります.
結果:24(バイト数を返す)
同級ディレクトリでjsonを生成する.txtファイルで内容は
補足ソース:
Fprintf:
Fprint:
Fprintln:
Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
Fprint(w io.Writer, a ...interface{}) (n int, err error)
Fprintln(w io.Writer, a ...interface{}) (n int, err error)
Fprintf()はformat形式の説明子に基づいてコンテンツをフォーマットしてファイルに書き込み、コンテンツが書き込まれたバイトとエラーであることを返します.
Fprint()とFprintln()は、デフォルトのフォーマットでコンテンツをファイルに書き込みます.違いはprint型とprintln型と一致する.
Fprintlnを例に挙げると、他の類似点があります.
package main
import (
"fmt"
"log"
"os"
)
func main() {
testRetFile, err := os.OpenFile("./json.txt", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Println(err)
}
num, err := fmt.Fprintln(testRetFile, "do you love me, my dear")
if err != nil {
log.Println(err)
}
fmt.Println(num)
}
結果:24(バイト数を返す)
同級ディレクトリでjsonを生成する.txtファイルで内容は
do you love me, my dear
補足ソース:
Fprintf:
// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
n, err = w.Write(p.buf)
p.free()
return
}
Fprint:
// Fprint formats using the default formats for its operands and writes to w.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrint(a)
n, err = w.Write(p.buf)
p.free()
return
}
Fprintln:
// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintln(a)
n, err = w.Write(p.buf)
p.free()
return
}