Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>  // for the memcmp function
  4.  
  5. #include "arr_dbl_t.h"
  6. #include "read_l7a.h"
  7.  
  8. #define T2A_BASE_CAP 4
  9.  
  10. int read_l7a(const char *filename, arr_dbl_t *ad)
  11. {
  12.   // Zero out *ad in case of failure.
  13.   ad->arr = NULL;
  14.   ad->len = ad->cap = 0;
  15.  
  16.   FILE *fp = fopen(filename, "rb");
  17.   char first4read[4], trailer_first4[4];
  18.   unsigned int el_count, trailer_count;
  19.   double *storage;
  20.   size_t read_count;
  21.  
  22.   if (fp == NULL)
  23.     return RL7A_OPEN_FAIL;
  24.  
  25.   read_count = fread((void *) first4read, 1, 4, fp);
  26.   if (read_count != 4)
  27.     return RL7A_TOO_SHORT;
  28.  
  29.   // memcmp returns 0 if two blocks of bytes of the same len
  30.   // match exactly.
  31.   if (memcmp((void *) first4read, (void *) L7A_FIRST_4, 4) != 0)
  32.     return RL7A_BAD_HEADER;
  33.  
  34.   read_count = fread((void *) &el_count, sizeof(unsigned int), 1, fp);
  35.   if (read_count != 1)
  36.     return RL7A_TOO_SHORT;
  37.  
  38.   storage = malloc(el_count * sizeof(double));
  39.   if (storage == NULL)
  40.     return RL7A_MALLOC_FAIL;
  41.  
  42.   read_count = fread((void *) storage, sizeof(double), el_count, fp);
  43.   if (read_count != el_count) {
  44.     free(storage);
  45.     return RL7A_TOO_SHORT;
  46.   }
  47.  
  48.   read_count = fread((void *) trailer_first4, 1, 4, fp);
  49.   if (read_count != 4) {
  50.     free(storage);
  51.     return RL7A_TOO_SHORT;
  52.   }
  53.   read_count = fread((void *) &trailer_count, sizeof(unsigned int), 1, fp);
  54.   if (read_count != 1) {
  55.     free(storage);
  56.     return RL7A_TOO_SHORT;
  57.   }
  58.   if (memcmp((void *) trailer_first4, (void *) L7A_FIRST_4, 4) != 0
  59.       || el_count != trailer_count) {
  60.     free(storage);
  61.     return RL7A_BAD_TRAILER;    
  62.   }
  63.  
  64.   if (fclose(fp) != 0) {
  65.     free(storage);
  66.     return RL7A_CLOSE_FAIL;
  67.   }
  68.  
  69.   ad->arr = storage;
  70.   ad->len = el_count;
  71.   ad->cap = el_count;
  72.   return RL7A_SUCCESS;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement