Go語言讀取文字檔案的方法如下。
使用內建的ioutil package的ReadFile(filename string) ([]byte, error)。輸入參數filename為檔案路徑名稱,輸出第一個參數為[]byte為文字檔內容的byte陣列;第二個參數error為錯誤,若讀取檔案錯誤時才有值,若無錯誤則為nil。
例如hello.txt內容如下:
Hello World!
main.go讀取同目錄中的hello.txt。
main.go
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
b, err := ioutil.ReadFile("hello.txt")
if err != nil {
log.Fatal(err) // if err exists log fetal and exit
}
str := string(b)
fmt.Println(str) // Hello World!
}
沒有留言:
張貼留言