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 58 59 60 61 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
int main(int argc, char* argv[]) {
// file contains:
// * number of doubles (4 bytes)
// * doubles based on above count (8 byte each)
// * string count (4 bytes)
// * for each string
// * string length (4 bytes)
// * string characters (1 byte each)
FILE* file = fopen("strings_in_binary.bin", "rb");
// read in numbers size
int numbers_count;
fread(&numbers_count, sizeof(numbers_count), 1, file);
printf("numbers: %d\n", numbers_count);
// read in numbers
double* numbers = malloc(sizeof(*numbers) * numbers_count);
fread(numbers, sizeof(*numbers), numbers_count, file);
// read in strings size
int strings_count;
fread(&strings_count, sizeof(strings_count), 1, file);
printf("strings: %d\n", strings_count);
// read in strings
char** strings = malloc(sizeof(*strings) * strings_count);
for (int i = 0; i < strings_count; i++) {
int string_length;
fread(&string_length, sizeof(string_length), 1, file);
char* string = malloc(sizeof(*string) * (string_length + 1));
fread(string, sizeof(*string), string_length, file);
string[string_length] = '\0';
strings[i] = string;
}
fread(strings, sizeof(*strings), strings_count, file);
// close after we are done reading
fclose(file);
for (int i = 0; i < numbers_count; i++) {
printf("%.9f\n", numbers[i]);
}
for (int i = 0; i < strings_count; i++) {
printf("%s\n", strings[i]);
free(strings[i]);
}
free(strings);
free(numbers);
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.