golang 文件操作
golang 文件操作
打开文件
在 golang 中,用 os.Open()
来打开文件,将返回一个文件实例 *File
和错误 err
,文件实例调用 Close()
方法来关闭文件
1 | package main |
写文件的打开方式又略有不同,需要另外指定参数,用 os.OpenFile()
打开,该方法签名如下,参数在后面写文件部分介绍
1 | func OpenFile(name string, flag int, perm FileMode) (*File, error) |
读取文件
读取文件有多种方式,速度可以测试一下再选用
File.Read
文件实例自带的操作bufio
带缓冲的IO,速度快,读到内存中缓冲,发起读写操作时会先冲缓冲中获取数据ioutil
重点是方便,里面一些操作有封装bufio
库ioutil.ReadAll
ioutil.Read
示例代码,分别是文件实例直接读取和循环、bufio
库读取、逐行读取、ioutil
库读取的内容
1 | package main |
假设有文件 ./tmp.txt
,内容如下:
1 | hello world1! |
运行结果
1 | file.Read: |
文件写入
需要写文件时,需要用 os.OpenFile()
指定操作模式打开文件,得到文件实例后进行写入,看下它的签名
filename
文件名flag
是操作模式,在os
包中有定义这些常量可以用,多个之间可以用|
拼接perm
指定文件权限,为一个八进制数,读写执行分别为(r
: 04,w
: 02,x
: 01)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// flag常量定义的部分
const (
// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.(只读)
O_WRONLY int = syscall.O_WRONLY // open the file write-only.(只写)
O_RDWR int = syscall.O_RDWR // open the file read-write.(可读可写)
// The remaining values may be or'ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.(追加写)
O_CREATE int = syscall.O_CREAT // create a new file if none exists.(不存在将创建)
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.(与创建搭配使用,文件必须不存在)
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.(用同步IO,不写缓冲直接落盘)
O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.(清空再写)
)
// OpenFile 函数签名
func OpenFile(name string, flag int, perm FileMode) (*File, error)
写文件示例,可以看到 ioutil
是封装的比较方便使用,;另外 bufio
因为有缓冲,所以有个刷盘操作
1 | package main |
刚接触,备忘。
Comments