Daniel YC Lin
Daniel YC Lin

Reputation: 16002

Read a binary file written by C in Go

What's the proper way to reading a binary file written by C? I've a C header file, there are some 'struct's. Is it possible to use these header file instead of manual re-write them in Go.

/* sample.h */
#define HEADER_SIZE 2048 //* large then sizeof(header)
typedef struct {
    uint8_t version;
    uint8_t endian;
    uint32_t createTime;
} header;

typedef struct {
    uint64_t data1;
    uint32_t data2;
    char name[128];
} record;

Here is my starting Go program with pseudo code

package "main"
// #include "sample.h"
import "C"
func main() {
  f, _ := os.Open("sample_file")
  // read(buf, HEADER_SIZE) and print out
  // use structure header to decode the buf
  // while not end of file {
  //    read(buf, sizeof(record) and print out
  // }
}

Upvotes: 1

Views: 1083

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54325

Read them using the encoding/binary package that you can find at https://golang.org/pkg/encoding/binary/

You can use binary.Read to read into a Go struct. You'll need to account for the padding the C version will add. In your example, default padding would put 2 pad bytes before createTime.

Upvotes: 1

Related Questions