英文:
Is there a API to read a line from a reader, but to limit the length of returned line?
问题
原型将是:
(reader *Reader) ReadLineWithMaxLength (delim byte, max int) (line []byte, err error)
当找到delim或达到max长度时,它会返回一行。
英文:
The prototype would be:
(reader *Reader) ReadLineWithMaxLength (delim byte, max int) (line []byte, err error)
It returns a line when either the delim is found or max length is reached.
答案1
得分: 2
我不认为有一个直接的函数,但是使用io.LimitReader
来实现一个函数是很简单的。
func ReadLimitedLine(r io.Reader, delim byte, max int64) ([]byte, error) {
l, err := bufio.NewReader(io.LimitReader(r, max)).ReadBytes(delim)
if err != nil && err != io.EOF {
return nil, err
}
// ReadBytes函数会将分隔符包含在返回值中
return bytes.TrimSuffix(l, []byte{delim}), nil
}
英文:
I don't think there is a direct function, but implementing one using io.LimitReader
is straightforward.
func ReadLimitedLine(r io.Reader, delim byte, max int64) ([]byte, error) {
l, err := bufio.NewReader(io.LimitReader(r, max)).ReadBytes(delim)
if err != nil && err != io.EOF {
return nil, err
}
// ReadBytes includes the delimiter in return value
return bytes.TrimSuffix(l, []byte{delim}), nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论