dongsi4815
2017-06-07 16:38
浏览 227
已采纳

使用buffo.read读取文件时的Golang动态大小调整片

I have a problem where, I need to use bufio.read to read a tsv file line by line and I need to record how many bytes each line Ive read is.

The problem is, It seems like I can't just initialize an empty slice and pass it into bufio.read and expect the slice to contain the entire line of the file.

file, _ := os.Open("file.tsv")

reader := bufio.NewReader(file)

b := make([]byte, 10)
for {
    bytesRead, err:= reader.Read(b)
    fmt.Println(bytesRead, b)
    if err != nil {
        break
    }
}

So, for this example, since I specified the slice to be 10 bytes, the reader will read at most 10 bytes even if the line is bigger than 10 bytes.

However:

file, _ := os.Open("file.tsv")

reader := bufio.NewReader(file)

b := byte{} //or var b []byte
for {
    bytesRead, err:= reader.Read(b)
    fmt.Println(bytesRead, b)
    if err != nil {
        break
    }
}

This will always read 0 bytes and I assume its because the buffer is length 0 or capacity 0.

How do I read a file Line by line, save the entire line in a variable or buffer, and return exactly how many bytes Ive read?

Thanks!

图片转代码服务由CSDN问答提供 功能建议

我有一个问题,我需要使用bufio.read逐行读取tsv文件,我需要 记录Ive读取的每一行有多少字节。

问题是,似乎我不能只初始化一个空切片并将其传递到bufio.read并期望该切片包含文件的整个行。

  file,_:= os.Open(“ file.tsv”)
 
reader:= bufio.NewReader(file)
 
b:= make([  ] byte,10)
for {
 bytesRead,err:= reader.Read(b)
 fmt.Println(bytesRead,b)
 if err!= nil {
 break 
} 
} 
    
 
 

因此,在此示例中,由于我将切片指定为10个字节,因此即使该行大于10个字节,阅读器也最多可以读取10个字节。 / p>

但是:

  file,_:= os.Open(“ file.tsv”)
 
reader:= bufio.NewReader  (file)
 
b:= byte {} //或var b [] byte 
for {
 bytesRead,err:= reader.Read(b)
 fmt.Println(bytesRead,b)
如果err  != nil {
 break 
} 
} 
   
 
 

这将始终读取0个字节,我认为它是因为缓冲区的长度为0或容量为0。

如何逐行读取文件,将整行保存在变量或缓冲区中,并确切返回Ive读取的字节数?

谢谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douyingmou1389 2017-06-07 16:41
    最佳回答

    If you want to read line by line, and you're using a buffered reader, use the buffered reader's ReadBytes method.

    line,err := reader.ReadBytes('
    ')
    

    This will give you a full line, one line at a time, regardless of byte length.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题