doufu7464 2017-06-13 18:27
浏览 72

从字节偏移开始读取文件的一行,直到换行

I am using os.ReadAt() to read certain rows in a csv/tsv file. However, I don't know how many bytes are in that row, I just need to read the line starting at the byte offset I specify until the newline.

buffer = make([]byte, 46)
os.ReadAt(buffer, 64) //Read at byte offset 64 and put contents in buffer

However, this only allows me to read 46 bytes of the line in. Is there any way to read the entire line until the newline?

Thanks

Update:

I just create a struct that holds the offset and line length.. Should've done this in the beginning.. my bad

  • 写回答

1条回答 默认 最新

  • dongmu1989 2017-06-13 18:47
    关注

    One way is use the bufio pkg. An example of this is the following:

    fd, err := os.Open("your_file.csv")
    if err != nil { //error handler
        log.Println(err)
        return
    }
    
    reader := bufio.NewReader(fd) // creates a new reader
    
    _, err = reader.Discard(64) // discard the following 64 bytes
    if err != nil { // error handler
        log.Println(err)
        return
    }
    
    // use isPrefix if is needed, this example doesn't use it
    // read line until a new line is found
    line, _, err := reader.ReadLine() 
    if err != nil { // error handler
        log.Println(err)
        return
    }
    fmt.Println(string(line))
    

    Another way to read the line, you can use fd.Seek(64,0) to jump to a specific byte like

    _, err = fd.Seek(64, 0)  // Set the current position for the fd
    if err != nil { // error handler
        log.Println(err)
        return
    }
    

    And afterward use the reader to read the line.

    reader := bufio.NewReader(fd)
    
    line, _, err := reader.ReadLine()
    if err != nil {
        log.Println(err)
        return
    }
    fmt.Println(string(line))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算