On Thu, 19 Jan 2017 00:05:46 -0800 (PST)
hui zhang <fastfad...@gmail.com> wrote:

> check below link
> 
> http://stackoverflow.com/questions/1821811/how-to-read-write-from-to-file-using-golang
> 
> It offer 3 ways.
> os
> *bufio*
> *ioutil*

There's just a single way to read a file -- using the Read() method on
values of type *os.File.  That's because this method function in the
end uses an appropriate low-level OS call which reads data from an
opened file, and trust me -- the wrapping around such a call
implemented in os.File.Read() is very very thin.

All the other things you referred to are not "methods to read a file" --
they are *approaches* to do that using a strategy which suits your
application best.

Several points to understand this:

* os.File.Read() is unbuffered: each time you call it, it, in turn,
  calls into the OS kernel.  Calling into kernel is *slow,* so when you
  just need to read the file's data from start to end in chunks of some
  size (or varying sizes), the best strategy is to use buffering -- that
  is, on each read round, to read as much as possible (available) so
  that the next read operation will be served from a buffer and no call
  to the OS will be made.

  OK, so there's bufio.Reader for this.

* os.File.Read() is free to read less data than you asked it for.
  That is, you can pass it a slice of length 4000, but it's free to
  return just a single byte.  That's not Go -- that's how OSes work.

  So if you need to read exactly 4000 bytes, you can certainly roll
  your own looping logic, but io.ReadFull() exists for exactly this
  purpose.

TL;DR
Any "non-standard method to read a file" you may encounter in the
standard library is -- in the end -- just a wrapper around the io.Reader
interface implemented by values of type *os.File.  They provide various
convenient ways to access the file using the best pattern for the task
at hand.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to