golang 檔案讀寫彙總

2021-10-05 15:46:17 字數 1682 閱讀 9726

檔案開啟

os.

open

() 返回唯讀模式的檔案描述符

os.openfile

0666)

o_rdonly:唯讀模式(read-only)

o_wronly:只寫模式(write-only)

o_rdwr:讀寫模式(read-write)

) o_create:檔案不存在就建立(create a new file if none exists.

) o_excl:與 o_create 一起用,構成乙個新建檔案的功能,它要求檔案必須不存在(used with o_create, file must not exist)

o_sync:同步方式開啟,即不使用快取,直接寫入硬碟

o_trunc:開啟並清空檔案

檔案讀寫
os包

f, err := os.

openfile()

讀: f.

read

() 走系統呼叫 效能較低

寫: f.

write

() 走系統呼叫 效能較低

ioutil包

讀檔案 readall/readfile 讀取整個檔案 不適合大檔案

寫檔案 writefile()

bufio包 (常用的包,讀寫介面靈活)

讀檔案 n, err :=

read

(p [

]byte

) 按塊讀取 注意此函式返回的讀取長度 p[

0:n]才是每次讀取的內容

readline

() 預設緩衝區為4096 如果有長度》

4096的行 不建議用此函式

readbytes

('\n'

) 指定分隔符讀取

readstring

('\n'

) 指定分隔符讀取

總之 如果按快讀取用read 按行讀取用readbytes或readstring 謹慎使用readline

寫檔案 write/writestring/writebyte/writerune 支援位元組串 字串 單位元組 utf-

8 用完記得write.

flush

()

大檔案讀取的兩種方式

1 逐行讀取

func

loadtofile

(src io.reader, dst io.writer)

} dstbuf.

flush()

return

}line, err := br.

readline()

如果一行超過4096則會截斷

建議用 br.

readstring

('\n'

) 或者 br.

readbytes

()

2 分片讀取
func

loadtofilewithbuffer

(src io.reader, dst io.writer, buffer [

]byte)}

dstbuf.

flush()

return

}

Golang 讀 寫檔案

檔案的讀寫是程式語言的常見操作之一,這裡講一些goang 讀取檔案的相關操作。讀取檔案有三種方式 具體實現如下 1 將檔案整個讀入記憶體package main import os io ioutil fmt func main defer file.close content,err ioutil...

go lang 讀寫檔案操作

參考備份 寫程式離不了檔案操作,這裡總結下 go語言檔案操作。一 建立與開啟 建立檔案函式 func create name string file file,err error func newfile fd int,name string file 具體見官網 開啟檔案函式 func open ...

Golang 檔案讀寫操作

package main import fmt io log os path filepath strconv func main strfile strdir testfile.txt fmt.println file to open is strfile 開啟檔案,如果沒有,那麼建立,設定為讀寫...