Go 自学:文件的写入和读取

首先,使用os.Create()函数建立一个文件。

接着,使用io.WriteString()函数将内容写入文件。

最后,使用os.ReadFile()函数读取文件内容。

注意,这里读取的文件内容是data byte,我们需要使用string()函数将其转换为字符串。

go 复制代码
package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	content := "This needs to go in a file."

	file, err := os.Create("./mygofile.txt")
	checkNilErr(err)

	length, err := io.WriteString(file, content)
	checkNilErr(err)

	fmt.Println("length is: ", length)
	defer file.Close()

	readFile("./mygofile.txt")

}

func readFile(filename string) {
	databyte, err := os.ReadFile(filename)
	checkNilErr(err)

	fmt.Println("Text data inside the file is \n", string(databyte))
}

func checkNilErr(err error) {
	if err != nil {
		panic(err)
	}
}

输出为:

length is: 27

Text data inside the file is

This needs to go in a file.

相关推荐
猫头虎7 小时前
2025最新OpenEuler系统安装MySQL的详细教程
linux·服务器·数据库·sql·mysql·macos·openeuler
木子.李3477 小时前
ssh连接远程服务器相关总结
运维·服务器·ssh
BD_Marathon8 小时前
SpringBoot——辅助功能之切换web服务器
服务器·前端·spring boot
necessary65310 小时前
使用Clion查看linux环境中的PG源码
linux·运维·服务器
代码N年归来仍是新手村成员10 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
AOwhisky13 小时前
Linux逻辑卷管理:从“固定隔间”到“弹性存储池”的智慧
linux·运维·服务器
翼龙云_cloud13 小时前
阿里云渠道商:如何使用弹性伸缩来实现计算资源的弹性配置?
服务器·阿里云·云计算
05大叔13 小时前
大事件Day02
运维·服务器
五仁火烧14 小时前
Vue3 项目的默认端口行为
服务器·vue.js·nginx·容器·vue
C Yu小白14 小时前
Linux系统调用与文件操作详解
linux·运维·服务器