首页 > golang > #yyds干货盘点#go语言文件操作示例详解
2019
08-17

#yyds干货盘点#go语言文件操作示例详解

1.golang读文件

1.1 整个文件读取

func readFile(){
filePath := "D:/phone.txt"
data,err := ioutil.ReadFile(filePath) //这里返回的data是一个字节切片
if err!=nil{
fmt.Println("File reading error", err)
}
fmt.Println(string(data))
}

1.2 按行读取

func readFile(){
filePath := "D:/phone.txt"
file,err := os.open(filepath)
if err!=nil{
fmt.Println("File reading error", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lineText := scanner.Text() //一行行读取
fmt.Println(string(lineText))
}
}

1.3 分块读取

func readFile(){
filePath := "D:/phone.txt"
file,err := os.open(filepath)
if err != nil {
return err
}
defer f.Close()
buf := make([]byte, 1024) //一次读取多少1025个字节
bfRd := bufio.NewReader(file)
for {
n, err := bfRd.Read(buf)
os.Stdout.Write(buf[:n)
if err != nil { //遇到任何错误立即返回,并忽略 EOF 错误信息
if err == io.EOF {
return nil
}
return err
}
}

2.golang写文件

2.1 msg写入文件

func writeFile(msg string)
filePath := "D:/phone.txt"
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
fmt.Println("文件打开失败", err)
return
}
//及时关闭file句柄
defer file.Close()
//写入文件时,使用带缓存的 *Writer
write := bufio.NewWriter(file)
write.WriteString(msg) //write.Write([]byte(msg)) 两种写法
//Flush将缓存的文件真正写入到文件中
write.Flush()
}

2.2 openfile的flag参数

// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
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.
O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.
)
中文解释:
O_RDONLY 以只读文式打开文件。
O_WRONLY 以只写方式打开文件。
O_RDWR 以读写方式打开文件
O_APPEND 以追加方式打开文件,写入的数据将追加到文件尾。
O_CREATE 当文件不存在时创建文件。
O_EXCL 与 O_CREATE 一起使用,当文件已经存在时 Open 操作失败。
O_SYNC 以同步方式打开文件。每次 write 系统调用后都等待实际的物理 I/O 完成后才返回,默认(不使用该标记)是使用缓冲的,也就是说每次的写操作是写到系统内核缓冲区中,等系统缓冲区满后才写到实际存储设备。
O_TRUNC 如果文件已存在,打开时将会清空文件内容。必须于 O_WRONLY 或 O_RDWR 配合使用。截断文件,需要有写的权限。

3.golang删除文件

func delFile()  {
filePath := "D:/phone.txt"
err := os.Remove(filePath)
if err != nil {
// 删除失败
fmt.Println("文件删除失败", err)
} else {
// 删除成功
fmt.Println("文件删除成功")
}
}

4.os下库函数

用到以下包

import (
"bufio"
"fmt"
"io/ioutil"
"os"
)

下面是一些常用库函数

#yyds干货盘点#go语言文件操作示例详解_文件删除



作者:golang中国
golang中国

本文》有 1414 条评论

留下一个回复