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
#include <stdio.h>
#include <stdlib.h>

typedef struct _ThreeDNamedPoint {
    int x, y, z;  // separate lines is nicer, but this is acceptable
    char name[10];
} ThreeDNamedPoint;

void print_point(ThreeDNamedPoint p) {
    printf("x=%d, y=%d, z=%d, name=%s\n", p.x, p.y, p.z, p.name);
}
int main(int argc, char* argv[]) {
    ThreeDNamedPoint p = {.x=5, .y=6, .z=7, .name="polyester"};

    FILE* fp = fopen("tdnp.bin", "w");
    // fwrite(…) essentially copies data from memory to file.
    fwrite(&p, sizeof(p), 1, fp);
    fclose(fp);
    print_point(p);

    fp = fopen("tdnp.bin", "r");
    // fread(…) essentially copies data from a file to memory.
    ThreeDNamedPoint p_copy; // not initializing because fread will do that for us
    fread(&p_copy, sizeof(p_copy), 1, fp);
    fclose(fp);
    print_point(p_copy);

    // For error handling, you will want to store the return value of
    // fread(…) and fwrite(…), which will be the number of objects read/written.

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2017 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.