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
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值