亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Go 中的結構更新 mmap 文件

使用 Go 中的結構更新 mmap 文件

Go
HUX布斯 2022-10-04 15:57:15
與將結構寫入映射內存文件(mmap)類似,如何將結構寫入 mmap 文件或使用 Go 中的結構更新 mmap 文件?假設我的二進制文件以二進制標頭開頭type MVHD struct {    Version      byte    Flags        [3]byte    DateCreated  time.Time    DateModified time.Time    TimeUnit        uint32 // time unit per second (default = 600)    DurationInUnits uint64 // time length (in time units)    Raw []byte // undecoded data after decoded bits above}假設我想將其映射為內存文件并更新字段,這可能嗎?DateModified(我在Go中對mmap的有限閱讀是它只能通過字節數組訪問,但我確信有一種方法可以通過結構來訪問它。我在這里找到了一個使用,但它太復雜了,我無法掌握基本思想)reflect
查看完整描述

1 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

您可以使用編碼/二進制來讀/寫固定大小的結構。此方法是可移植的,不依賴于內存布局、編譯器或 CPU 體系結構。例如:

// Note: using uint32 instead of time.Time for decoding.

// Convert to time.Time afterwards if needed.

type MVHD struct {

    Version          byte

    Flags            [3]byte

    DateCreatedSecs  uint32

    DateModifiedSecs uint32


    TimeUnit        uint32 // time unit per second (default = 600)

    DurationInUnits uint64 // time length (in time units)

}


// ..or use binary.BigEndian - whichever is correct for your data.

var endian = binary.LittleEndian


func decode(rd io.Reader) (*MVHD, error) {

    var header MVHD 

    if err := binary.Read(rd, endian, &header); err != nil {

        return nil, err

    }

    return &header, nil

}      

用于將 轉換為 .這將允許您使用 mmap 數據。bytes.NewReader[]byteio.Readerdecode


或者,您可以手動對其進行解碼:


func decode2(buf []byte) (*MVHD, error) {

    if len(buf) < 24 {

        return nil, errors.New("not enough data")

    }  

    return &MVHD{

        Version:          buf[0],

        Flags:            [3]byte{buf[1], buf[2], buf[3]},

        DateCreatedSecs:  binary.LittleEndian.Uint32(buf[4:8]),

        DateModifiedSecs: binary.LittleEndian.Uint32(buf[8:12]),

        TimeUnit:         binary.LittleEndian.Uint32(buf[12:16]),

        DurationInUnits:  binary.LittleEndian.Uint64(buf[16:24]),

    }, nil

}

同樣,您可以使用二進制文件就地更新數據。字節順序調用:Put


func updateDateModified(buf []byte, t uint32) error {

    if len(buf) < 12 {

        return errors.New("not enough data")

    }

    binary.LittleEndian.PutUint32(buf[8:12], t)

    return nil

}


查看完整回答
反對 回復 2022-10-04
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號