1. 程式人生 > 其它 >Golang語言社群-檔案操作

Golang語言社群-檔案操作

Golang語言社群-檔案操作

go語言支援的檔案操作很多 1、傳統的檔案操作 匯入檔案操作需要的包

import "os"

1、檔案的開啟

f := os.Open(filepath)

2、檔案的讀取

f.Read([]byte)

3、檔案的關閉

f.Close()

openfile, err := os.Open(“test.go”)//正確開啟檔案返回err := nil //這裡如果檔案開啟異常,則丟擲錯誤 if err != nil { //panic函式會終止程式的執行,並且列印錯誤相當於C/C++中的assert()函式 panic(“open file error”) } //defer相當於C++中的解構函式,在程式結束之前,執行其後的函式 defer openfile.Close() //分配記憶體,儲存讀取的資料 buff := make([]byte, 512) for n, err := openfile.Read(buff); err == nil; n, err = openfile.Read(buff) { fmt.Print(string(buff[:n])) } //檔案載入錯誤,丟擲異常 if err != nil { panic(fmt.Sprintf(“Read occurs error: %s”, err)) }