Golang dynamic sizing slice when reading a file using buffo.read

huangapple go评论96阅读模式
英文:

Golang dynamic sizing slice when reading a file using buffo.read

问题

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

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

所以,对于这个例子,由于我指定了切片为10个字节,即使行的长度大于10个字节,读取器也最多只会读取10个字节。

然而:

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

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

谢谢!

英文:

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!

答案1

得分: 0

如果你想逐行读取,并且正在使用缓冲读取器,可以使用缓冲读取器的ReadBytes方法。

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

这将以一次一行的方式给你完整的行,无论字节长度如何。

英文:

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('\n')

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

huangapple
  • 本文由 发表于 2017年6月8日 00:38:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/44418361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定