dongtu1789 2014-10-21 15:34
浏览 44
已采纳

在Go中将多个结构写入文件

me and my group are new to Go and we have a "Header" struct and multiple "Record" structs that we're trying to write to a file. However, whenever we try to update the Header struct in the file by rewriting to it, the rest of the file gets messed up.

We are using Encode / Decode: (dataFile is returned from os.Open)

dataFile.Seek(header.FreePtr,0) //seek to free space - could we just refactor and seek to end of file? 
encoder := gob.NewEncoder((dataFile))
err = encoder.Encode(record)
if err != nil {
    panic(err)
}

dataFile.Seek(header.FreePtr, 0)
decoder = gob.NewDecoder(dataFile)
r := Record{}
err = decoder.Decode(&r)
fmt.Println(r.Key)
fmt.Println(r.Width)
fmt.Println(string(r.Data))

header.FreePtr += int64(unsafe.Sizeof(record.Key)) + int64(unsafe.Sizeof(record.Width))+ int64(record.Width)
dataFile.Seek(0, 0)
encoder = gob.NewEncoder(dataFile)
err = encoder.Encode(header)
if err != nil {
    panic(err)
}

Is there a better way to do this? If we don't need to update the header, would that solve our problems? (Encoding to the end of the file all the time instead of trying to update something at the beginning between adding records). Ideally we might need a header later though, so if we could keep it, that would be great.

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongxie7683 2014-10-21 15:57
    关注

    Your file get messed up because the length of the header changes when you update it. That is why some formats reserve the last N bytes of the File for the header. In your way you would have to

    1. Read the whole file in memory
    2. Update the Header
    3. Rewrite Header + Records back to the file

    Or Allocate a FIXED size for the header at the start of your file and only update that part of it.

    Keep in mind that this a problem with any programming language, not just Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab