#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;
	}

	fclose(fo);
	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 )
	{
		fclose(fi);
		return false;
	}

	fclose(fi);
	*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) )
		{
			printf("oops..\n");
			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) )
		{
			printf("oops..\n");
			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);
	}
}
