55 lines
1.2 KiB
Markdown
55 lines
1.2 KiB
Markdown
# Go 文件操作
|
|
|
|
## 1.文本文件
|
|
|
|
### 1.1.创建
|
|
|
|
```go
|
|
f,err := os.Create(fileName)
|
|
defer f.Close()
|
|
if err !=nil {
|
|
fmt.Println(err.Error())
|
|
} else {
|
|
_,err=f.Write([]byte("要写入的文本内容"))
|
|
checkErr(err)
|
|
}
|
|
```
|
|
|
|
### 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))
|
|
}
|
|
```
|
|
|
|
打开模式如下:
|
|
|
|
```go
|
|
//打开方式
|
|
const (
|
|
//只读模式
|
|
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.
|
|
//追加内容
|
|
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 // if possible, truncate file when opened.
|
|
)
|
|
```
|