douzhantao2857 2018-10-18 10:48
浏览 590
已采纳

如何在Golang中删除大文件的前N个字节? [重复]

This question already has an answer here:

I have a big file about 10G, and i want to delete the first 10 bytes of this file.

If I use ioutil.ReadFile(), the whole file will be allocated to memory. This can't be done!

Another idea is that I read this file line by line. And after removing the data, I should write the remain data line by line. In this way, the memory can be saved, but if there exists a better way? Like split the reader or split the file?

</div>
  • 写回答

1条回答 默认 最新

  • doumeng2637 2018-10-18 10:55
    关注

    On most filesystems you can't "cut" a part out from the beginning or from the middle of a file, you can only truncate it at the end.

    The easiest to achieve what you want is to open the source file, skip the part you want to strip off (use seeking), open the destination file and simply copy from the source to the destination.

    For seeking (skipping), use File.Seek(). For copying between the files, use io.Copy().

    This is how it can be done:

    fin, err := os.Open("source.txt")
    if err != nil {
        panic(err)
    }
    defer fin.Close()
    
    fout, err := os.Create("dest.txt")
    if err != nil {
        panic(err)
    }
    defer fout.Close()
    
    // Offset is the number of bytes you want to exclude
    _, err = fin.Seek(10, io.SeekStart)
    if err != nil {
        panic(err)
    }
    
    n, err := io.Copy(fout, fin)
    fmt.Printf("Copied %d bytes, err: %v", n, err)
    

    Note that the above code will get the result file you want in a new file. If you want the "new" to be the old (meaning you don't want a different file), after the above operation (if it succeeds) delete the original file and rename the new one to the old.

    This is how you can do that final step:

    if err := os.Remove("source.txt"); err != nil {
        panic(err)
    }
    
    if err := os.Rename("dest.txt", "source.txt"); err != nil {
        panic(err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信