讀取檔案內容的 Go 語言程式
pre.prettyprint{width:99%!important;} a.demo{top:12px!important; float:right!important;}
要讀取檔案的內容,我們可以執行以下步驟 -
- 我們可以建立一個名為**test.txt** 的檔案。
- 使用 **defer** 語句進行清理。
- 編寫字串的內容。
- 呼叫 **ReadFile()** 方法讀取檔案。
- **ReadFile** 讀取由檔名命名的檔案並返回內容。
- 列印檔案的文字內容。
示例
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
)
func CreateFile() {
file, err := os.Create("test.txt")
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
defer file.Close()
_, err = file.WriteString("Welcome to Tutorials Point")
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
}
func ReadFile() {
fileName := "test.txt"
data, err := ioutil.ReadFile(fileName)
if err != nil {
log.Panicf("failed reading data from file: %s", err)
}
fmt.Printf("\n%s", data)
}
func main() {
CreateFile()
ReadFile()
}輸出
Welcome to Tutorials Point
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP