dtv11049 2012-10-10 21:22
浏览 14
已采纳

如何改善此文件的读取代码

I currently have this piece of code that will read a file line by line (delimited by a )

file, _ := os.Open(filename) //deal with the error later
defer file.Close()

buf := bufio.NewReader(file)
for line, err := buf.ReadString('
'); err != io.EOF; line, err = buf.ReadString('
')
{
    fmt.Println(strings.TrimRight(line, "
"))
}

However I don't feel comfortable with writing buf.ReadString(" ") twice in the for loop, does anyone have any suggestions for improvement?

  • 写回答

2条回答 默认 最新

  • dongmian5325 2012-10-11 00:40
    关注

    bufio.ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.

    If buf.ReadString(' ') returns an error other than io.EOF, for example bufio.ErrBufferFull, you will be in an infinite loop. Also, if the file doesn't end in a ' ', you silently ignore the data after the last ' '.

    Here's a more robust solution, which executes buf.ReadString(' ') once.

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "os"
        "strings"
    )
    
    func main() {
        filename := "FileName"
        file, err := os.Open(filename)
        if err != nil {
            fmt.Println(err)
            return
        }
        defer file.Close()
        buf := bufio.NewReader(file)
        for {
            line, err := buf.ReadString('
    ')
            if err != nil {
                if err != io.EOF || len(line) > 0 {
                    fmt.Println(err)
                    return
                }
                break
            }
            fmt.Println(strings.TrimRight(line, "
    "))
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图