golang 文件读写
使用 io/ioutil 进行读写文件
io/ioutil 其中提到了两个方法
func ReadFile
func ReadFile(filename string) ([]byte, error)
ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.
func WriteFile
func WriteFile(filename string, data []byte, perm os.FileMode) error
WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm; otherwise WriteFile truncates it before writing.
读文件:
1 | package main |
写文件:
1 | package main |
使用 os 进行读写文件
os 包打开文件的方法
func Open
func Open(name string) (*File, error)
Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.
读文件:
1 | file, err := os.Open(path) |
func OpenFile
需要提供文件路径、打开模式、文件权限
func OpenFile(name string, flag int, perm FileMode) (*File, error)
OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.
读文件:
1 | package main |
读方法
1 | package main |
寻址取偏移量:
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
// Seek sets the offset for the next Read or Write on file to offset,interpreted
// according to whence: 0 means relative to the origin of the file, 1 means
// relative to the current offset, and 2 means relative to the end.
// It returns the new offset and an error, if any.
// The behavior of Seek on a file opened with O_APPEND is not specified.
写方法
1 | package main |
几种读取文件方法速度比较
1 | package main |
运行结果:
1 | Cost time 4.0105ms |
底层实现
底层 IO
1 | //os提供的功能 |
缓冲 IO
1 | bufio.Reader/Writer |
标准 IO 操作数据流向路径:数据—>进程缓冲(用户态)—>内核缓存区(内核态)—>磁盘
为什么包一层 buf,buf 读的时候读一大块,给你读取的时候,你只需要从 buf 里面去读一点数据,下次再读一点数据,不用每次读取都去调用系统库,buf 写的时候,当写满一大块的时候,才真正调用系统写,因为不用每次写都去调用系统写,这样会提高性能,但数据可能丢失或是不一致的情况
任务
内存大小为 4G 的电脑给 10G 的文件排序?