Go文件操作(新建打開寫入讀取刪除關(guān)閉)學(xué)習(xí)筆記
Go 操作文本文件
Go
操作文本文件時,與其它語言一樣也有新建文件、打開文件、寫文件、讀文件、刪除文件等操作,我們一起先看下 Go
操作文本文件的 API。
1. 新建文件
//返回 File 的內(nèi)存地址, 錯誤信息;通過 os 庫調(diào)用 func Create(name string) (file *File, err Error)
//返回文件的內(nèi)存地址, 通過 os 庫調(diào)用 func NewFile(fd int, name string) *File
2. 打開文件
//返回 File 的內(nèi)存地址, 錯誤信息;通過 os 庫調(diào)用 func Open(name string) (file *File, err Error)
//返回 File 的內(nèi)存地址, 錯誤信息, 通過 os 庫調(diào)用 func OpenFile(name string, flag int, perm unit32) (file *File, err Error)
3. 寫入文件
//寫入一個 slice, 返回寫的個數(shù), 錯誤信息, 通過 File 的內(nèi)存地址調(diào)用 func (file *File).Write(b []byte) (n int, err Error)
//從 slice 的某個位置開始寫入, 返回寫的個數(shù), 錯誤信息,通過 File 的內(nèi)存地址調(diào)用 func (file *File).WriteAt(b []byte, off int64) (n int, err Error)
//寫入一個字符串, 返回寫的個數(shù), 錯誤信息, 通過 File 的內(nèi)存地址調(diào)用 func (file *File).WriteString(s string) (ret int, err Error)
4. 讀取文件
//讀取一個 slice, 返回讀的個數(shù), 錯誤信息, 通過 File 的內(nèi)存地址調(diào)用 func (file *File).Read(b []byte) (n int, err Error)
//從 slice 的某個位置開始讀取, 返回讀到的個數(shù), 錯誤信息, 通過 File 的內(nèi)存地址調(diào)用 func (file *File).ReadAt(b []byte, off int64) (n int, err Error)
4. 刪除文件
//傳入文件的路徑來刪除文件,返回錯誤個數(shù) func Remove(name string) Error
5. 關(guān)閉文件
func (f *File) Close() error
使用示例
package main import ( "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 表示到達EOF break } os.Stdout.Write(buf) } }
輸出結(jié)果:
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文件操作(新建打開寫入讀取刪除關(guān)閉)學(xué)習(xí)筆記的詳細內(nèi)容,更多關(guān)于Go文件操作的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
基于go實例網(wǎng)絡(luò)存儲協(xié)議詳解
這篇文章主要為大家介紹了基于go實例網(wǎng)絡(luò)存儲協(xié)議詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03Go語言學(xué)習(xí)之將mp4通過rtmp推送流媒體服務(wù)的實現(xiàn)方法
對音視頻一直是小白,決定沉下心來,好好研究一下音視頻知識,下面這篇文章主要給大家介紹了關(guān)于Go語言學(xué)習(xí)之將mp4通過rtmp推送流媒體服務(wù)的實現(xiàn)方法,需要的朋友可以參考下2022-12-12如何基于Golang實現(xiàn)Kubernetes邊車模式
本文介紹了如何基于Go實現(xiàn)Kubernetes Sidecar模式,并通過實際示例演示創(chuàng)建Golang實現(xiàn)的微服務(wù)服務(wù)、Docker 容器化以及在 Kubernetes 上的部署和管理,感興趣的朋友一起看看吧2024-08-08Go 并發(fā)實現(xiàn)協(xié)程同步的多種解決方法
這篇文章主要介紹了Go 并發(fā)——實現(xiàn)協(xié)程同步的多種解決方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08Goland調(diào)節(jié)字體大小的設(shè)置(編輯區(qū),terminal區(qū),頁面字體)
這篇文章主要介紹了Goland調(diào)節(jié)字體大小的設(shè)置(編輯區(qū),terminal區(qū),頁面字體),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12