V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
dongtingyue
V2EX  ›  Go 编程语言

求教 go 读取文件并记录偏移量的正确姿势

  •  
  •   dongtingyue · 2022-03-31 14:03:32 +08:00 · 1297 次点击
    这是一个创建于 729 天前的主题,其中的信息可能已经有所发展或是发生改变。

    目前是

    f.Seek(size,0)
    bfRd := bufio.NewReader(f)
    line, _, err := bfRd.ReadLine()
    offset +=len(string(line))+2
    ...省略
    

    文件内容这样

    aaaaa
    bbbbb
    cccc
    

    程序计算的偏移量会大于实际文件 2 个字节,因此只能读取结束后减 2 。有其他更简洁的方式么?

    shadeofgod
        1
    shadeofgod  
       2022-03-31 14:27:24 +08:00
    看文档,ReadLine tries to return a single line, not including the end-of-line bytes.

    Most callers should use ReadBytes('\n') or ReadString('\n') instead or use a Scanner.
    dongtingyue
        2
    dongtingyue  
    OP
       2022-03-31 14:35:55 +08:00
    JKeita
        3
    JKeita  
       2022-03-31 15:14:29 +08:00
    这 2 字节是换行吧?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2754 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:04 · PVG 20:04 · LAX 05:04 · JFK 08:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.