Go語言檔案操作

2021-10-03 11:32:55 字數 2784 閱讀 8757

檔案的開啟和關閉

os.open()函式能夠開啟乙個檔案,返回乙個*file和乙個err。對得到的檔案例項呼叫close()方法能夠關閉檔案。

為了防止檔案忘記關閉,我們通常使用defer註冊檔案關閉語句。

讀取檔案

file.read()

read方法定義如下:

func

(f *file)

read

(b [

]byte

)(n int

, err error

)

它接收乙個位元組切片,返回讀取的位元組數和可能的具體錯誤,讀到檔案末尾時會返回0和io.eof。

package main

import

("fmt"

"io"

"os"

)func

main()

defer file.

close()

buf :=

make([

]byte

,128

)var content [

]byte

forif err1 !=

nil content =

(content, buf[

0:n]

...)

} fmt.

println

(string

(content)

)}

每次讀取128byte的資料,成功讀取之後新增給切片content,當讀到檔案末尾時候,跳出迴圈,列印content。

os.openfile()函式能夠以指定模式開啟檔案,從而實現檔案寫入相關功能。

func

openfile

(name string

, flag int

, perm filemode)

(*file,

error

)

name:要開啟的檔名 flag:開啟檔案的模式。 模式有以下幾種:

模式含義

os.o_wronly

只寫os.o_create

建立檔案

os.o_rdonly

唯讀os.o_rdwr

讀寫os.o_trunc

清空追加

write和writestring

package main

import

("fmt"

"os"

)func

main()

defer file.

close()

buf :=

"如果有一天我變得很有錢"

file.

write([

]byte

(buf)

) file.

writestring

("我就可以吧所以人都留在我身邊,每天吃吃喝喝,聊聊天"

)}

file.write和file.writestring都返回寫入的位元組數和錯誤型別兩個值,區別在於,write需要傳入byte型別,writestring直接傳入字串型別。

bufio是在file的基礎上封裝了一層api,支援更多的功能。

package main

import

("bufio"

"fmt"

"io"

"os"

)func

main()

defer file.

close()

reader := bufio.

newreader

(file)

forif err1 !=

nil fmt.

print

(buf)

}}

同file的方法一樣,如果需要對檔案進行寫入操作,那麼必須使用openfile函式開啟檔案是否賦予寫入許可權和開啟方式。

package main

import

("bufio"

"fmt"

"os"

)func

main()

defer file.

close()

writer := bufio.

newwriter

(file)

_, err1 := writer.

writestring

("不同擔心明天或離別"

)if err1 !=

nil writer.

flush()

//寫入存在緩衝區,此操作將緩衝區寫入檔案

}

io/ioutil包的readfile方法能夠讀取完整的檔案,只需要將檔名作為引數傳入。

package main

import

("fmt"

"io/ioutil"

)func

main()

fmt.

println

(string

(content)

)}

package main

import

("fmt"

"io/ioutil"

)func

main()

}

go語言 檔案操作

os.open 函式能夠開啟乙個檔案,返回乙個 file和乙個err。對得到的檔案例項呼叫close 方法能夠關閉檔案。package main import fmt os func main 關閉檔案 file.close 為了防止檔案忘記關閉,我們通常使用defer註冊檔案關閉語句。read方法...

Go語言檔案操作

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

Go語言檔案操作

輸入流和輸出流 os.file 封裝所有檔案相關操作,file是乙個結構體 官方文件 開啟檔案使用的是os包下的open,openfile函式 func open name string file file,err error open開啟乙個檔案用於讀取。如果操作成功,返回的檔案物件的方法可用於讀...