dream989898 2016-10-04 18:20
浏览 355
已采纳

Golang-如何克服bufio的Scan()缓冲区限制?

I am using the bufio scanner's .Scan() method to read text file lines. However when I reach a certain size in the file lines, the scanner no longer allows me to read, it just returns an empty line.

How should I configure the buffer to take in larger amounts of data?

bigfile.txt is just a file with many integers in a line separated by a space. For example, 40000 integers in one line. (note that it works for file lines of 10000 integers and less, but not 40000 for example)

234 544 765 45 34 67 67 87 98 43 [... n = 40000 ]

func main() {
    readInputFile("bigfile.txt")
}

func readInputFile(name string) {
    inFile, _ := os.Open(name)
    defer inFile.Close()

    scanner := bufio.NewScanner(inFile)

    for scanner.Scan() {
        line := scanner.Text()
        fmt.Printf(line)
    }
}
  • 写回答

1条回答 默认 最新

  • dsjpqpdm620596 2016-10-05 02:07
    关注

    According to documentation and corresponding source code, by default Scanner uses internal buffer in which the capacity is 64K. In your case, the internal buffer is not sufficient for storing 40000 integers. Set the buffer to be used by scanner before calling Scan, i.e.

    scanner := bufio.NewScanner(inFile)
    
    //adjust the capacity to your need (max characters in line)
    const maxCapacity = 512*1024  
    buf := make([]byte, maxCapacity)
    scanner.Buffer(buf, maxCapacity)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端