Why rd := bufio.NewReader(fi)?  'fi' implements io.Reader.  Try: err = 
binary.Read(fi, binary.LittleEndian, &pi) instead.  Then fi.Seek(...) will 
 manipulate your io.Reader.  [An 
example: https://github.com/clbanning/rfile/blob/master/reverse.go#L57.]


On Wednesday, January 18, 2017 at 11:22:48 PM UTC-7, hui zhang wrote:
>
> I am using encoding/binary to read/write (struct)data to/from file.
> Some times , I need to seek in the file while reading .
> how to do this in go. 
> Check the code below
>
>
>
> package main
>
> import (
>    _ "bytes"
>    "fmt"
>    _ "math"
>
>    "bufio"
>    "encoding/binary"
>    "os"
> )
>
> func main() {
>    var pi float64
>    //b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40,
>    //         0x78, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}
>    //buf := bytes.NewReader(b)
>    //err := binary.Read(buf, binary.LittleEndian, &pi)
>    //if err != nil {
>    // fmt.Println("binary.Read failed:", err)
>    //}
>    //fmt.Println(pi)
>    //// Output: 3.141592653589793
>    //err = binary.Read(buf, binary.LittleEndian, &pi)
>    //if err != nil {
>    // fmt.Println("binary.Read failed:", err)
>    //}
>    //fmt.Println(pi)
> //------------------------------------------------------------
>    // open output file
>    fo, err := os.Create("./output.bin")
>    if err != nil {
>       panic(err)
>    }
>
>    // make a write buffer
>    var fl1 float64 = 3.13
>    var fl2 float64 = 3.14
>    w := bufio.NewWriter(fo)
>    err = binary.Write(w, binary.LittleEndian, fl1)
>    if err != nil {
>       fmt.Println("binary.Write failed:", err)
>    }
>    err = binary.Write(w, binary.LittleEndian, fl2)
>    if err != nil {
>       fmt.Println("binary.Write failed:", err)
>    }
>    w.Flush()
>    // close fo on exit and check for its returned error
>    if err := fo.Close(); err != nil {
>       panic(err)
>    }
>
>    //------------------------------------------------------------
>    fi, err := os.Open("./output.bin")
>    if err != nil {
>       panic(err)
>    }
>    // close fi on exit and check for its returned error
>    defer func() {
>       if err := fi.Close(); err != nil {
>          panic(err)
>       }
>    }()
>
>    rd := bufio.NewReader(fi)
>    err = binary.Read(rd, binary.LittleEndian, &pi)
>    if err != nil {
>       fmt.Println("binary.Read failed:", err)
>    }
>    fmt.Println(pi)
>
>    fi.seek()////?????
>
>    err = binary.Read(rd, binary.LittleEndian, &pi)
>    if err != nil {
>       fmt.Println("binary.Read failed:", err)
>    }
>    fmt.Println(pi)
>
> }
>
>

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