LoginSignup
0
0

More than 5 years have passed since last update.

Go file読み込み まとめ

Posted at

はじめに

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)
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0