How can I “pack” and “write” a struct to a file using C so that:
struct a {
uint64_t a;
char* b;
uint16_t c;
} a;
a b;
b.a = 3;
b.b = "Hello";
b.c = 4;
gets written to the file as
00 00 00 00 00 00 00 03 48 65 6c 6c 6f 00 00 04
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In C, you’ll have to code a function to do this for you. You can’t just blat the structure out to disk because
bis a pointer that makes no sense without the backing string. And, unless you know (and can control) how your compiler packs its structures, you’re better off with a utility function anyway, even without pointers.And, as if that wasn’t enough, you should output the length of the string as well so you know how many bytes to read back.
You’ll be looking for something like: