Go文件操作(新建打开写入读取删除关闭)学习笔记
作者:wohu 程序员的自我进化
这篇文章主要为大家介绍了Go文件操作(新建打开写入读取删除关闭)学习笔记,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
Go 操作文本文件
Go 操作文本文件时,与其它语言一样也有新建文件、打开文件、写文件、读文件、删除文件等操作,我们一起先看下 Go 操作文本文件的 API。
1. 新建文件
//返回 File 的内存地址, 错误信息;通过 os 库调用 func Create(name string) (file *File, err Error)
//返回文件的内存地址, 通过 os 库调用 func NewFile(fd int, name string) *File
2. 打开文件
//返回 File 的内存地址, 错误信息;通过 os 库调用 func Open(name string) (file *File, err Error)
//返回 File 的内存地址, 错误信息, 通过 os 库调用 func OpenFile(name string, flag int, perm unit32) (file *File, err Error)
3. 写入文件
//写入一个 slice, 返回写的个数, 错误信息, 通过 File 的内存地址调用 func (file *File).Write(b []byte) (n int, err Error)
//从 slice 的某个位置开始写入, 返回写的个数, 错误信息,通过 File 的内存地址调用 func (file *File).WriteAt(b []byte, off int64) (n int, err Error)
//写入一个字符串, 返回写的个数, 错误信息, 通过 File 的内存地址调用 func (file *File).WriteString(s string) (ret int, err Error)
4. 读取文件
//读取一个 slice, 返回读的个数, 错误信息, 通过 File 的内存地址调用 func (file *File).Read(b []byte) (n int, err Error)
//从 slice 的某个位置开始读取, 返回读到的个数, 错误信息, 通过 File 的内存地址调用 func (file *File).ReadAt(b []byte, off int64) (n int, err Error)
4. 删除文件
//传入文件的路径来删除文件,返回错误个数 func Remove(name string) Error
5. 关闭文件
func (f *File) Close() error
使用示例
package main
import (
"fmt"
"os"
)
func main() {
fileName := "/home/wohu/gocode/src/test.txt"
writeFile(fileName)
readFile(fileName)
}
func writeFile(fileName string) {
file, err := os.Create(fileName)
if err != nil {
fmt.Println(err)
return
}
for i := 0; i <= 5; i++ {
outStr := fmt.Sprintf("%s:%d\n", "hello, world", i)
file.WriteString(outStr)
file.Write([]byte("abcd\n"))
}
file.Close()
}
func readFile(fileName string) {
file, err := os.Open(fileName)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
buf := make([]byte, 1024)
for {
n, _ := file.Read(buf)
if n == 0 {
//0 表示到达EOF
break
}
os.Stdout.Write(buf)
}
}输出结果:
wohu@wohu:~/gocode/src$ ls
github.com golang.org hello.go test.txt
wohu@wohu:~/gocode/src$ cat test.txt
hello, world:0
abcd
hello, world:1
abcd
hello, world:2
abcd
hello, world:3
abcd
hello, world:4
abcd
hello, world:5
abcd
wohu@wohu:~/gocode/src$
以上就是Go文件操作(新建打开写入读取删除关闭)学习笔记的详细内容,更多关于Go文件操作的资料请关注脚本之家其它相关文章!
