LoginSignup
38
17

More than 5 years have passed since last update.

Go言語でのファイル読み取り

Last updated at Posted at 2018-06-22

Go言語でのファイル読み取り

環境

go version go1.9.4
Zorin OS 12.3

概要

Go言語を使ったファイルの読み取りプログラムについてまとめる

ファイル読み取り処理

まず読み取るファイルを作成します。内容は何でもOK。

test.txt
これはファイル読み取り処理用に作られたファイルです
テスト用

読み取りプログラムを記述。
ファイル読み取りに必要なものは2つ。
byte型スライスとosパッケージ。

test_read.go
package main

import(
    "fmt"
    "os"
)

func main(){
    fmt.Println("ファイル読み取り処理を開始します")
    // ファイルをOpenする
    f, err := os.Open("test.txt")
    // 読み取り時の例外処理
    if err != nil{
        fmt.Println("error")
    }
    // 関数が終了した際に確実に閉じるようにする
    defer f.Close()

    // バイト型スライスの作成
    buf := make([]byte, 1024)
    for {
        // nはバイト数を示す
        n, err := f.Read(buf)
        // バイト数が0になることは、読み取り終了を示す
        if n == 0{
            break
        }
        if err != nil{
            break
        }
        // バイト型スライスを文字列型に変換してファイルの内容を出力
        fmt.Println(string(buf[:n]))
    }
}

出力
ファイル読み取り処理を開始します
これはファイル読み取り処理用に作られたファイルです
テスト用

ファイル読み取り処理2

io/ioutilパッケージを使うと、読み取り部分がスッキリする。

test_read2.go
package main

import(
    "fmt"
    "os"
    "io/ioutil"
)

func main(){
    fmt.Println("ファイル読み取り処理を開始します")
    // ファイルをOpenする
    f, err := os.Open("test.txt")
    if err != nil{
        fmt.Println("error")
    }
    defer f.Close()

    // 一気に全部読み取り
    b, err := ioutil.ReadAll(f)
    // 出力
    fmt.Println(string(b))
}
出力
ファイル読み取り処理を開始します
これはファイル読み取り処理用に作られたファイルです
テスト用

出力結果も同じなので問題ない。

38
17
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
38
17