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