1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include "clog.h"
enum { MAX_ROOM_NUM_SIZE=16 };
// You would think sizeof(Point) would be 1 + 4 + 4 + 16, but compiler may add padding to make data
// align with multiples of 4 in memory. By default, the above type will occupy 28 bytes, not 25.
//
#pragma pack(1) // This means pack fields to align by multiples of 1 byte (in other words, NO PADDING ALLOWED).
typedef struct {
char c;
int x;
int y;
char name[MAX_ROOM_NUM_SIZE]; // fixed string length limits cause major security holes
} Point;
// G
void print_point(Point p) {
printf("p.x == %d p.y == %d p.name == \"%s\"\n", p.x, p.y, p.name);
}
void write_point_to_file(const char* path, Point p) {
FILE* fp = fopen(path, "w");
fwrite(&p, sizeof(p), 1, fp); // copy bytes from memory to disk
fclose(fp);
}
Point read_point_from_file(const char* path) {
Point p;
FILE* fp = fopen(path, "r");
fread(&p, sizeof(p), 1, fp); // copy bytes from disk to memory
fclose(fp);
return p;
}
int main(int argc, char* argv[]) {
Point here = { .x = 0xba, .y=0x88, .name="MATH 175" };
print_point(here);
write_point_to_file("here.bin", here); // file extensions are just a convention
log_addr(&here);
Point there = read_point_from_file("here.bin");
print_point(there);
log_addr(&there);
printf("sizeof(there) == %zd\n", sizeof(there));
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2020 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.