fork(1) download
  1. #include <stdio.h> // for fread, fwrite, fopen, FILE, fclose
  2. #include <stdlib.h> // for NULL, EXIT_FAILURE.
  3. #include <stddef.h> // for size_t
  4. #include <stdbool.h> // for bool.
  5.  
  6. struct unko
  7. {
  8. double x;
  9. double y;
  10. };
  11.  
  12. typedef struct unko unko;
  13.  
  14. bool file_writer(char const *filename, unko const data[static 1], size_t element_count)
  15. {
  16. FILE *fo;
  17. if ( element_count < 1
  18. || (fo = fopen(filename, "wb")) == NULL
  19. || fwrite(&element_count, sizeof element_count, 1, fo) != 1
  20. || fwrite(data, sizeof(unko), element_count, fo) != element_count )
  21. {
  22. return false;
  23. }
  24.  
  25. fclose(fo);
  26. return true;
  27. }
  28.  
  29. // データレイアウト
  30. // [0] 要素数。整数。
  31. // :
  32. // [7]
  33. //
  34. // [7 + 0] 1番目のxの開始
  35. // :
  36. // [7 + 8] 1番目のyの開始
  37. //
  38. // [7 + i * 16 + 0] i+1番目のxの開始
  39. // :
  40. // [7 + i * 16 + 7] i+1番目のxの終了
  41. // [7 + i * 16 + 8] i+1番目のyの開始
  42. // :
  43. // [7 + i * 16 + 15] i+1番目のyの終了
  44. bool file_reader(char const *filename, unko data[], size_t data_size, size_t *p_read_count)
  45. {
  46. size_t element_count;
  47. FILE *fi = fopen(filename, "rb");
  48. if ( fi == NULL
  49. || fread(&element_count, sizeof element_count, 1, fi) != 1
  50. || element_count > data_size
  51. || fread(data, sizeof(unko), element_count, fi) != element_count )
  52. {
  53. fclose(fi);
  54. return false;
  55. }
  56.  
  57. fclose(fi);
  58. *p_read_count = element_count;
  59. return true;
  60. }
  61.  
  62. int main()
  63. {
  64. char const *filename = "unko.dat";
  65.  
  66. {
  67. unko test_data[] = { { .x = 1.234, .y = 2.345 }, { .x = 0.001, .y = -0.987 }, { .x = 3.14, .y = 2.718 } };
  68. if ( !file_writer(filename, test_data, sizeof test_data / sizeof *test_data) )
  69. {
  70. printf("oops..\n");
  71. return EXIT_FAILURE;
  72. }
  73. }
  74.  
  75. {
  76. unko test_data2[100];
  77. size_t element_count;
  78. if ( !file_reader(filename, test_data2, sizeof test_data2 / sizeof *test_data2, &element_count) )
  79. {
  80. printf("oops..\n");
  81. return EXIT_FAILURE;
  82. }
  83.  
  84. printf("unko count = %zu\n", element_count);
  85.  
  86. for ( int i = 0; i < (int)element_count; i++ )
  87. printf("unko #%d: x=%.3f, y=%.3f\n", i, test_data2[i].x, test_data2[i].y);
  88. }
  89. }
  90.  
Runtime error #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
oops..