[go-nuts]how does ReadString() handle io.EOF?

2,509 views
Skip to first unread message

Ejwt Fourier

unread,
Dec 3, 2012, 11:00:49 PM12/3/12
to golang-nuts
I was playing around file io in Go, here is an confusing example I wrote:

package main

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

func main() {
    fi, err := os.Open("test.txt")  // test.txt contains only THREE chars: abc (no tailing \n)
    if err != nil { panic(err) }
    defer fi.Close()
    r := bufio.NewReader(fi)
    line, err := r.ReadString('\n')
    if err == io.EOF { return }
    fmt.Print(line)
    fmt.Println(err)
}

The output is:
abc
<nil>

I quote the package doc of ReadString here:
func (b *Reader) ReadString(delim byte) (line string, err error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.

According to this statement, IMO, ReadString should have got io.EOF, and there shouldn't be any output at all.  did the code append a '\n' to the file automatically?




andrey mirtchovski

unread,
Dec 3, 2012, 11:24:21 PM12/3/12
to Ejwt Fourier, golang-nuts
that is not the behaviour i'm seeing on linux and osx at tip. on both
operating systems the program exits without output and if i comment
out the check for err == io.EOF, the program prints 'abcEOF'.

can you verify that the file contains only 'abc' and no line feeds of
any kind? also, what OS are using, what Go version?
> --
>
>

Andrew Gerrand

unread,
Dec 3, 2012, 11:29:17 PM12/3/12
to andrey mirtchovski, Ejwt Fourier, golang-nuts
I can corroborate what Andrey says.


Andrew


--



Steve McCoy

unread,
Dec 4, 2012, 11:21:30 AM12/4/12
to golan...@googlegroups.com
If you used vim to create test.txt, then there is probably a newline at the end of it. Some other editors do this, but that's the main one I can think of.

"echo abc > test.txt" would also add one.

Reply all
Reply to author
Forward
0 new messages