3 回答
TA贡献1824条经验 获得超6个赞
例如,
package main
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"os"
)
type Index struct {
A int32
B int32
C int32
D int64
}
func readIndex(r io.Reader) (Index, error) {
var index Index
var buf [24]byte
_, err := io.ReadFull(r, buf[:])
if err != nil {
return index, err
}
index.A = int32(binary.LittleEndian.Uint32(buf[0:4]))
index.B = int32(binary.LittleEndian.Uint32(buf[4:8]))
index.C = int32(binary.LittleEndian.Uint32(buf[8:12]))
index.D = int64(binary.LittleEndian.Uint64(buf[16:24]))
return index, nil
}
func main() {
f, err := os.Open("index.bin")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
defer f.Close()
r := bufio.NewReader(f)
indexes := make([]Index, 0, 1024)
for {
index, err := readIndex(r)
if err != nil {
if err == io.EOF {
break
}
fmt.Fprintln(os.Stderr, err)
return
}
indexes = append(indexes, index)
}
fmt.Println(indexes)
}
输出:
[{1 2 3 4} {5 6 7 8} {9 10 11 12}]
输入:
00000000 01 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 |................|
00000010 04 00 00 00 00 00 00 00 05 00 00 00 06 00 00 00 |................|
00000020 07 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 |................|
00000030 09 00 00 00 0a 00 00 00 0b 00 00 00 00 00 00 00 |................|
00000040 0c 00 00 00 00 00 00 00 |........|
TA贡献1772条经验 获得超8个赞
我发现添加填充字段不太舒服。我找到了一个更好的方法。
下面是完美运行的新 golang 读取代码:
package main
import (
"fmt"
"os"
"io"
"io/ioutil"
"unsafe"
)
type Index struct {
A int32
B int32
C int32
// Pad int32
D int64
}
func main() {
indexSize := unsafe.Sizeof(Index{})
fp, _ := os.Open("index.bin")
defer fp.Close()
info, _ := fp.Stat()
fileSize := info.Size()
entryCnt := fileSize / int64(indexSize)
reader := io.Reader(fp)
allBytes, _ := ioutil.ReadAll(reader)
readSlice := *((*[]Index)(unsafe.Pointer(&allBytes)))
realLen := len(allBytes) / int(indexSize)
readSlice = readSlice[:realLen]
fmt.Printf("After read:\n%#v\n", readSlice)
}
输出:
After read:
[]main.Index{main.Index{A:1, B:2, C:3, D:4}, main.Index{A:5, B:6, C:7, D:8}, main.Index{A:9, B:10, C:11, D:12}}
此解决方案不需要显式填充字段。
这里的本质是,如果让golang将整个字节转换为Indexstruct的切片,它似乎能够很好地处理padding。
- 3 回答
- 0 关注
- 199 浏览
添加回答
举报