GO语言 使用Fprint系列写入文件

首先先了解Fp系列:

  • 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
}

 

你可能感兴趣的:(GO语言)