Xi 张熹
Xi 张熹

Reputation: 11071

Create a io.Reader from a local file

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) {

}

Upvotes: 134

Views: 157035

Answers (6)

Panda Zhang
Panda Zhang

Reputation: 39

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
}

Upvotes: -1

Ian Grant
Ian Grant

Reputation: 1

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

Upvotes: -2

spacether
spacether

Reputation: 2721

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
}

Upvotes: 10

Yandry Pozo
Yandry Pozo

Reputation: 5123

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)

Upvotes: 49

fabmilo
fabmilo

Reputation: 48330

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

Upvotes: 163

ANisus
ANisus

Reputation: 78075

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.

Upvotes: 57

Related Questions