delete first N bytes from a text file

前端 未结 1 1914
再見小時候
再見小時候 2021-01-29 14:02

Is there any function call or simple way to delete first N bytes from a text file in golang? Assuming that the file is contentiously appended by various go-routines, simultaneou

相关标签:
1条回答
  • 2021-01-29 14:37

    You need to do f.Seek to jump over first bytes and than do regular reading, see example:

    package main
    
    import (
        "fmt"
        "io"
        "io/ioutil"
        "os"
    )
    
    func main() {
        f, err := os.Open(os.Args[1])            // open file from argument
        if err != nil {
            fmt.Println(err)
            return
        }
    
        var skipBytes int64 = 5                  // how many bytes to skip
    
        _, err = f.Seek(skipBytes, io.SeekStart) // skipping first bytes
        if err != nil {
            fmt.Println(err)
            return
        }
    
        buffer := make([]byte, 1024)               // allocating buffer to read
        for {
            n, err := f.Read(buffer)               // reading
            fmt.Print(string(buffer[:n]))          // writing to console
            if err != nil {
                fmt.Printf("Err: %v\n", err)
                return
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题