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语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?