127

I would like to open a local file, and return a io.Reader. The reason is that I need to feed a io.Reader to a library I am using, like:

func read(r io.Reader) (results []string) {

}
1
  • 1
    Probably worth spending some time browsing around golang.org/pkg and, for the kind of thing it sounds like you're doing, the os, io, io/ioutil, and bufio.
    – twotwotwo
    Sep 5, 2014 at 3:31

6 Answers 6

156

os.Open returns an io.Reader

http://play.golang.org/p/BskGT09kxL

package main

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

var _ io.Reader = (*os.File)(nil)

func main() {
    fmt.Println("Hello, playground")
}
6
  • 38
    Heh, love the trick for showing that (*os.File) is an io.Reader without being able to Open files from the Playground.
    – twotwotwo
    Sep 5, 2014 at 5:15
  • 8
    @mschuett More or less: it's a nil pointer of the right type to point to an os.File. (In this case, you can't really do anything through it.) And the var _ io.Reader = (*os.File)(nil) assignment makes the compiler check that *os.File is an io.Reader (or else the assignment wouldn't be valid). If you go to the Playground and change *os.File to *os.Process you'll see the error it generates for things that don't satisfy the interface.
    – twotwotwo
    Feb 20, 2015 at 6:55
  • 3
    @fabrizioM where exactly in the documentation it says that *os.File implements a Reader. Otherwise, without this answer how you could figure out yourself from just reading an official doc? Ok, I see that func (f *File) Read(b []byte) (n int, err error), the same as in Reader. Aug 18, 2015 at 14:36
  • 1
    I think the example is too contrived to provide a solid answer. Answer suggests using os.Open(), but the example does not it, at least not in an obvious way, as one would expect from an example.
    – tutiplain
    Oct 12, 2021 at 15:56
  • 1
    @tutiplain This is a common pattern to ensure an interface is implemented properly. But a bit more explanation for beginners wouldn't harm, that's right.
    – NotX
    Feb 21, 2022 at 15:26
56

Use os.Open():

func Open(name string) (file *File, err error)

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

The returned value of type *os.File implements the io.Reader interface.

43

The type *os.File implements the io.Reader interface, so you can return the file as a Reader. But I recommend you to use the bufio package if you have intentions of read big files, something like this:

file, err := os.Open("path/file.ext")
// if err != nil { ... }

return bufio.NewReader(file)
4
  • 5
    Could you please elaborate on why you recommend bufio for large files?
    – Ciro Costa
    May 10, 2017 at 21:34
  • 1
    @CiroCosta if you have a huge file of Gbs you don't want to read it completely on memory, so for those cases we should use a buffer Aug 20, 2017 at 17:09
  • 1
    go's runtime uses buffers in sensible situations e.g. io.Copy will reuse underlying buffers if their interface is available - otherwise it will create an internal buffer
    – colm.anseo
    Feb 2, 2019 at 21:46
  • 1
    Thanks for path/file.ext. No other answer spelled out what os.File was.
    – Azurespot
    Aug 3, 2019 at 0:41
9

Here is an example where we open a text file and create an io.Reader from the returned *os.File instance f

package main

import (
    "io"
    "os"
)

func main() {
    f, err := os.Open("somefile.txt")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    var r io.Reader
    r = f
}
2
0

io.Reader is an interface, it`s doccument is here io.Reader, and the os.File implement this interface, so you can read an File struct to get an io.Reader.

the code example is :

package main

import (
 "os"
)

func main() {
 file, err := os.Read("example.txt")
 ...
 // the `file` is an io.Reader
}
-2

You can just use the file object returned from, say, os.Open as a reader. I believe this type discipline is called "Duck Typing". For example, in the go tour reader Exercise: rot13Reader you can replace the main() with this:

func main() {
   file, err := os.Open("file.txt") // For read access.
   if err != nil {
      log.Fatal(err)
   }

   r := rot13Reader{file}
   io.Copy(os.Stdout, &r)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.