How to dump a struct to a file

I have a packed struct, and i want to write it as is to a file, however os.write only accepts ^File and byte.

How do I do that?

1 Like

Does this solve the problem?

package main

import "core:os"
import "core:fmt"

Your_Struct :: struct {
	x: int,
	y: f32,
	z: bool,
}

main :: proc() {
	your_file, err := os.create("some_file.txt")
	assert(err == nil, "Failed to create a file")

	ys: Your_Struct
	ys_as_str := fmt.tprintfln("%#v", ys)

	os.write(your_file, transmute([]byte)ys_as_str)
}
2 Likes

Be aware that this only works if you have no pointer like type in Data, so no ^T, [^]T, []T or [dynamic]T. If you need to encode complicated data type as binary, there’s core/encoding/cbor.

package dump_struct

import "core:fmt"
import "core:os"
import "core:slice"

Data :: struct #packed {
	a: bool,
	b: u16,
	c: [12]byte,
}

main :: proc () {
	s0 := Data { true, 0x4455, "hello, world" }
	bs := slice.bytes_from_ptr(&s0, size_of(s0))

	err := os.write_entire_file("s.dat", bs)
	assert(err == nil)

	bs, err = os.read_entire_file("s.dat", context.allocator)
	assert(err == nil)
	// bs is allocated on the heap
	defer delete(bs)

	s1, ok := slice.to_type(bs, Data)
	assert(ok)

	fmt.printfln("written: %#v", s0)
	fmt.printfln("read: %#v", s1)
	assert(s0 == s1)
}
3 Likes

no it doesnt, it just write text lol i want to write the memory representation not a human readable string

this is what i was looking for. Thanks!