#include <stdio.h> // for fread, fwrite, fopen, FILE, fclose
#include <stdlib.h> // for NULL, EXIT_FAILURE.
#include <stddef.h> // for size_t
#include <stdbool.h> // for bool.
struct unko
{
double x;
double y;
};
typedef struct unko unko;
bool file_writer(char const *filename, unko const data[static 1], size_t element_count)
{
FILE *fo;
if ( element_count < 1
|| (fo
= fopen(filename
, "wb")) == NULL
|| fwrite(&element_count
, sizeof element_count
, 1, fo
) != 1 || fwrite(data
, sizeof(unko
), element_count
, fo
) != element_count
) {
return false;
}
return true;
}
// データレイアウト
// [0] 要素数。整数。
// :
// [7]
//
// [7 + 0] 1番目のxの開始
// :
// [7 + 8] 1番目のyの開始
//
// [7 + i * 16 + 0] i+1番目のxの開始
// :
// [7 + i * 16 + 7] i+1番目のxの終了
// [7 + i * 16 + 8] i+1番目のyの開始
// :
// [7 + i * 16 + 15] i+1番目のyの終了
bool file_reader(char const *filename, unko data[], size_t data_size, size_t *p_read_count)
{
size_t element_count;
FILE
*fi
= fopen(filename
, "rb"); if ( fi == NULL
|| fread(&element_count
, sizeof element_count
, 1, fi
) != 1 || element_count > data_size
|| fread(data
, sizeof(unko
), element_count
, fi
) != element_count
) {
return false;
}
*p_read_count = element_count;
return true;
}
int main()
{
char const *filename = "unko.dat";
{
unko test_data[] = { { .x = 1.234, .y = 2.345 }, { .x = 0.001, .y = -0.987 }, { .x = 3.14, .y = 2.718 } };
if ( !file_writer(filename, test_data, sizeof test_data / sizeof *test_data) )
{
return EXIT_FAILURE;
}
}
{
unko test_data2[100];
size_t element_count;
if ( !file_reader(filename, test_data2, sizeof test_data2 / sizeof *test_data2, &element_count) )
{
return EXIT_FAILURE;
}
printf("unko count = %zu\n", element_count
);
for ( int i = 0; i < (int)element_count; i++ )
printf("unko #%d: x=%.3f, y=%.3f\n", i
, test_data2
[i
].
x, test_data2
[i
].
y); }
}
I2luY2x1ZGUgPHN0ZGlvLmg+CQkvLyBmb3IgZnJlYWQsIGZ3cml0ZSwgZm9wZW4sIEZJTEUsI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