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 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R