How to find EOF while reading from a file

Worlock picture Worlock · Jan 22, 2013 · Viewed 32.8k times · Source

I am using the following code to read a file in Go:

spoon , err := ioutil.ReadFile(os.Args[1])
if err!=nil {
        panic ("File reading error")
}

Now I check for every byte I pick for what character it is. For example:

spoon[i]==' ' //for checking space

Likewise I read the whole file (I know there maybe other ways of reading it) but keeping this way intact, how can I know that I have reached EOF of the file and I should stop reading it further?

Please don't suggest to find the length of spoon and start a loop. I want a sure shot way of finding EOF.

Answer

peterSO picture peterSO · Jan 23, 2013

Use io.EOF to test for end-of-file. For example, to count spaces in a file:

package main

import (
    "fmt"
    "io"
    "os"
)

func main() {
    if len(os.Args) <= 1 {
        fmt.Println("Missing file name argument")
        return
    }
    f, err := os.Open(os.Args[1])
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    data := make([]byte, 100)
    spaces := 0
    for {
        data = data[:cap(data)]
        n, err := f.Read(data)
        if err != nil {
            if err == io.EOF {
                break
            }
            fmt.Println(err)
            return
        }
        data = data[:n]
        for _, b := range data {
            if b == ' ' {
                spaces++
            }
        }
    }
    fmt.Println(spaces)
}