Go 学习笔记(21)— 标准库 os 操作文件(新建、打开、写入、读取、删除、关闭文件)
生活随笔
收集整理的這篇文章主要介紹了
Go 学习笔记(21)— 标准库 os 操作文件(新建、打开、写入、读取、删除、关闭文件)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Go 操作文本文件時,與其它語言一樣也有新建文件、打開文件、寫文件、讀文件、刪除文件等操作。主要有兩個標準庫來提供這些操作,分別為 os 和 ioutil 。在該文中我們介紹 os 模塊。
1. 新建文件
func Create(name string) (file *File, err Error)
//返回 File 的內存地址, 錯誤信息;通過 os 庫調用
func NewFile(fd int, name string) *File
//返回文件的內存地址, 通過 os 庫調用
2. 打開文件
func Open(name string) (file *File, err Error)
//返回 File 的內存地址, 錯誤信息;通過 os 庫調用
func OpenFile(name string, flag int, perm unit32) (file *File, err Error)
//返回 File 的內存地址, 錯誤信息, 通過 os 庫調用
3. 寫入文件
//寫入一個 slice, 返回寫的個數, 錯誤信息, 通過 File 的內存地址調用
func (file *File).Write(b []byte) (n int, err Error)
//從 slice 的某個位置開始寫入, 返回寫的個數, 錯誤信息,通過 File 的內存地址調用
func (file *File).WriteAt(b []byte, off int64) (n int, err Error)
//寫入一個字符串, 返回寫的個數, 錯誤信息, 通過 File 的內存地址調用
func (file *File).WriteString(s string) (ret int, err Error)
4. 讀取文件
//讀取一個 slice, 返回讀的個數, 錯誤信息, 通過 File 的內存地址調用
func (file *File).Read(b []byte) (n int, err Error)
//從 slice 的某個位置開始讀取, 返回讀到的個數, 錯誤信息, 通過 File 的內存地址調用
func (file *File).ReadAt(b []byte, off int64) (n int, err Error)
4. 刪除文件
//傳入文件的路徑來刪除文件,返回錯誤個數
func Remove(name string) Error
5. 關閉文件
func (f *File) Close() error
6. 使用示例
package mainimport ("fmt""os"
)func main() {fileName := "/home/wohu/gocode/src/test.txt"writeFile(fileName)readFile(fileName)}func writeFile(fileName string) {file, err := os.Create(fileName)if err != nil {fmt.Println(err)return}for i := 0; i <= 5; i++ {outStr := fmt.Sprintf("%s:%d\n", "hello, world", i)file.WriteString(outStr)file.Write([]byte("abcd\n"))}file.Close()
}func readFile(fileName string) {file, err := os.Open(fileName)if err != nil {fmt.Println(err)return}defer file.Close()buf := make([]byte, 1024)for {n, _ := file.Read(buf)if n == 0 {//0 表示到達EOFbreak}os.Stdout.Write(buf)}
}
輸出結果:
wohu@wohu:~/gocode/src$ ls
github.com golang.org hello.go test.txt
wohu@wohu:~/gocode/src$ cat test.txt
hello, world:0
abcd
hello, world:1
abcd
hello, world:2
abcd
hello, world:3
abcd
hello, world:4
abcd
hello, world:5
abcd
wohu@wohu:~/gocode/src$
總結
以上是生活随笔為你收集整理的Go 学习笔记(21)— 标准库 os 操作文件(新建、打开、写入、读取、删除、关闭文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 哪些字属水好听的名字
- 下一篇: Go 学习笔记(22)— 并发(01)[