2

I am using os.ReadAt() to read certain rows in a csv/tsv file. However, I don't know how many bytes are in that row, I just need to read the line starting at the byte offset I specify until the newline.

buffer = make([]byte, 46)
os.ReadAt(buffer, 64) //Read at byte offset 64 and put contents in buffer

However, this only allows me to read 46 bytes of the line in. Is there any way to read the entire line until the newline?

Thanks

Update:

I just create a struct that holds the offset and line length.. Should've done this in the beginning.. my bad

Jason Piao
  • 67
  • 1
  • 6

1 Answers1

2

One way is use the bufio pkg. An example of this is the following:

fd, err := os.Open("your_file.csv")
if err != nil { //error handler
    log.Println(err)
    return
}

reader := bufio.NewReader(fd) // creates a new reader

_, err = reader.Discard(64) // discard the following 64 bytes
if err != nil { // error handler
    log.Println(err)
    return
}

// use isPrefix if is needed, this example doesn't use it
// read line until a new line is found
line, _, err := reader.ReadLine() 
if err != nil { // error handler
    log.Println(err)
    return
}
fmt.Println(string(line))

Another way to read the line, you can use fd.Seek(64,0) to jump to a specific byte like

_, err = fd.Seek(64, 0)  // Set the current position for the fd
if err != nil { // error handler
    log.Println(err)
    return
}

And afterward use the reader to read the line.

reader := bufio.NewReader(fd)

line, _, err := reader.ReadLine()
if err != nil {
    log.Println(err)
    return
}
fmt.Println(string(line))
Motakjuq
  • 1,669
  • 1
  • 6
  • 21
  • I have to step back in the file Im currently reading, so I can't just discard the next n bytes. I have to jump back to the top of the file sometimes. Can you put a negative number In discard? – Jason Piao Jun 13 '17 at 18:59
  • No, but you can use `file.seek()` and create another `bufio.Reader` if you need it. – Motakjuq Jun 13 '17 at 19:45
  • Yeah.. I was trying to avoid that.. but I guess thats the only option. Thanks! – Jason Piao Jun 13 '17 at 19:56