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

int main(int argc, char* argv[]) {
    FILE* file = fopen("strings_in_binary.bin", "wb");

    char* strings[] = {
        "Hello",
        "World",
        "String"
    };
    int strings_count = sizeof(strings) / sizeof(*strings);

    double numbers[] = { 0.5, 1.25, 123.111111111 };
    int numbers_count = sizeof(numbers) / sizeof(*numbers);
    // numbers:
    // * number count (4 bytes)
    // * numbers (4 bytes each) 
    fwrite(&numbers_count, sizeof(numbers_count), 1, file);
    fwrite(numbers, sizeof(*numbers), numbers_count, file);

    // strings:
    // * string count (4 bytes)
    // * for each string
    //     * string length (4 bytes)
    //     * string characters (1 byte each)
    // important: we cannot just write the address for each string,
    // that is no longer valid once this program terminates
    fwrite(&strings_count, sizeof(strings_count), 1, file);
    for (int i = 0; i < strings_count; i++) {
        int string_length = strlen(strings[i]);
        fwrite(&string_length, sizeof(string_length), 1, file);
        fwrite(strings[i], sizeof(**strings), string_length, file);
    }

    fclose(file);

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

© Copyright 2024 Alexander J. Quinn & David Burnett         This content is protected and may not be shared, uploaded, or distributed.