概述
首先先了解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语言 使用Fprint系列写入文件的全部内容,希望文章能够帮你解决GO语言 使用Fprint系列写入文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复