douao7937 2019-02-01 12:44
浏览 304

如何从文件中删除最后N个字节

I want to delete thelast N bytes from file in Go, My mean resize file without create new temp file and after block copy rename temp file.

I want to do this is read-write mode look like:

    // Read Write Mode
    file, err := os.OpenFile("C:\\Test.zip", os.O_RDWR, 0644)
    if err != nil {
        return err
    }

For example in .NET look like this:

FileInfo fi = new FileInfo("filename");
FileStream fs = fi.Open(FileMode.Open);

long bytesToDelete = 5000;
fs.SetLength (Math.Max(0, fi.Length - bytesToDelete));

fs.Close();
  • 写回答

1条回答 默认 最新

  • dongqiu3709 2019-02-01 12:52
    关注

    Actually, this is already implemented is the os.Truncate() function. But this function takes the new size. So to use this, you have to first get the size of the file. For that, you may use os.Stat().

    Wrapping it into a function:

    func truncateFile(name string, bytesToRemove int64) error {
        fi, err := os.Stat(name)
        if err != nil {
            return err
        }
    
        return os.Truncate(name, fi.Size()-bytesToRemove)
    }
    

    Using it to remove the last 5000 bytes:

    if err := truncateFile("C:\\Test.zip", 5000); err != nil {
        fmt.Println("Error:", err)
    }
    

    Another alternative is to use the File.Truncate() method for that. If we have an os.File, we may also use File.Stat() to get its size.

    This is how it would look like:

    func truncateFile(name string, bytesToRemove int64) error {
        f, err := os.OpenFile(name, os.O_RDWR, 0644)
        if err != nil {
            return err
        }
        defer f.Close()
    
        fi, err := f.Stat()
        if err != nil {
            return err
        }
    
        return f.Truncate(fi.Size() - bytesToRemove)
    }
    

    Using it is the same. This may be preferable if we're working on a file (we have it opened) and we have to truncate it. But in that case you'd want to pass os.File instead of its name to truncateFile().

    Note: if you try to remove more bytes than the file currently has, truncateFile() will return an error.

    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决