完善 Go 文件操作.
Signed-off-by: rick.chan <chenyang@autoai.com>
This commit is contained in:
parent
7ad0a36218
commit
ba1355eb5f
|
@ -1,8 +1,17 @@
|
|||
# Go 文件操作
|
||||
|
||||
## 1.文本文件
|
||||
os.File 封装了所有文件相关的操作,File 是一个结构体,有很多方法。
|
||||
|
||||
### 1.1.创建
|
||||
## 1.os 包
|
||||
|
||||
### 1.1.创建文件
|
||||
|
||||
```go
|
||||
func Create(name string) (file *File, err error)
|
||||
func NewFile(fd uintptr, name string) *File
|
||||
```
|
||||
|
||||
Create 方法示例如下:
|
||||
|
||||
```go
|
||||
f,err := os.Create(fileName)
|
||||
|
@ -15,21 +24,14 @@ if err !=nil {
|
|||
}
|
||||
```
|
||||
|
||||
### 1.2.读取
|
||||
### 1.2.打开文件
|
||||
|
||||
```go
|
||||
f, err := os.OpenFile(fileName, os.O_RDONLY,0600)
|
||||
defer f.Close()
|
||||
if err !=nil {
|
||||
fmt.Println(err.Error())
|
||||
} else {
|
||||
contentByte,err=ioutil.ReadAll(f)
|
||||
checkErr(err)
|
||||
fmt.Println(string(contentByte))
|
||||
}
|
||||
func Open(name string) (*File, error)
|
||||
func OpenFile(name string, flag int, perm FileMode) (*File, error)
|
||||
```
|
||||
|
||||
打开模式如下:
|
||||
perm 模式如下:
|
||||
|
||||
```go
|
||||
//打开方式
|
||||
|
@ -52,3 +54,87 @@ O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
|
|||
O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
|
||||
)
|
||||
```
|
||||
|
||||
### 1.3.获取文件状态
|
||||
|
||||
```go
|
||||
func (f *File) Stat() (fi FileInfo, err error)
|
||||
```
|
||||
|
||||
### 1.4.读取文件
|
||||
|
||||
```go
|
||||
func (f *File) Read(b []byte) (n int, err error)
|
||||
```
|
||||
|
||||
### 1.5.写入文件
|
||||
|
||||
```go
|
||||
func (f *File) Write(b []byte) (n int, err error)
|
||||
```
|
||||
|
||||
## 2.ioutil 包
|
||||
|
||||
### 2.1.读取
|
||||
|
||||
示例如下:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import(
|
||||
"io/ioutil"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main(){
|
||||
b,err := ioutil.ReadFile("C:/example.txt")
|
||||
|
||||
if err != nil{
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
fmt.Println(b)
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
```
|
||||
|
||||
### 2.2.写入
|
||||
|
||||
示例如下:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import(
|
||||
"io/ioutil"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main(){
|
||||
str := []byte("Hello,Go!")
|
||||
err := ioutil.WriteFile("C:/example.txt", str, 0644)
|
||||
if err != nil{
|
||||
panic(err)
|
||||
}else{
|
||||
fmt.Println("WriteFile Success!")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 3.bufio 包
|
||||
|
||||
### 3.1.读文件
|
||||
|
||||
```go
|
||||
func NewReader(rd io.Reader) *Reader
|
||||
func (b *Reader) Read(p []byte) (n int, err error)
|
||||
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
|
||||
```
|
||||
|
||||
### 3.2.写文件
|
||||
|
||||
```go
|
||||
func NewWriter(w io.Writer) *Writer
|
||||
func (b *Writer) Write(p []byte) (nn int, err error)
|
||||
```
|
||||
|
|
Loading…
Reference in New Issue