はじめに
goのファイルの読み込みについていちいちググるのがめんどくなってきたので忘備録
ioutil.ReadFile
ioutil.ReadFileを使う
かなり短くかけてよい
f, _ := ioutil.ReadFile("hello.txt")
fmt.Print(string(f))
byteのスライスを作成して読み込む
文字で結構byteを使うけどなんでなのかわかってない
とりあえず動く
f, _ := os.Open("hello.txt")
ary := make([]byte, 100)
f.Read(ary)
fmt.Println(string(b1))
bufio.NewScanner
bufio使うやつ
f, _ := os.Open("hello.txt")
scanner := bufio.NewScanner(f)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
readlineで読み込むやつ
f, err := os.Open("hello.txt")
if err != nil {
panic("error")
}
defer f.Close()
reader := bufio.NewReaderSize(f, 1024)
for {
line, _, err := reader.ReadLine()
fmt.Println(string(line))
if err == io.EOF {
break
} else if err != nil {
panic(err)
}
}