Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h> // for the memcmp function
- #include "arr_dbl_t.h"
- #include "read_l7a.h"
- #define T2A_BASE_CAP 4
- int read_l7a(const char *filename, arr_dbl_t *ad)
- {
- // Zero out *ad in case of failure.
- ad->arr = NULL;
- ad->len = ad->cap = 0;
- FILE *fp = fopen(filename, "rb");
- char first4read[4], trailer_first4[4];
- unsigned int el_count, trailer_count;
- double *storage;
- size_t read_count;
- if (fp == NULL)
- return RL7A_OPEN_FAIL;
- read_count = fread((void *) first4read, 1, 4, fp);
- if (read_count != 4)
- return RL7A_TOO_SHORT;
- // memcmp returns 0 if two blocks of bytes of the same len
- // match exactly.
- if (memcmp((void *) first4read, (void *) L7A_FIRST_4, 4) != 0)
- return RL7A_BAD_HEADER;
- read_count = fread((void *) &el_count, sizeof(unsigned int), 1, fp);
- if (read_count != 1)
- return RL7A_TOO_SHORT;
- storage = malloc(el_count * sizeof(double));
- if (storage == NULL)
- return RL7A_MALLOC_FAIL;
- read_count = fread((void *) storage, sizeof(double), el_count, fp);
- if (read_count != el_count) {
- free(storage);
- return RL7A_TOO_SHORT;
- }
- read_count = fread((void *) trailer_first4, 1, 4, fp);
- if (read_count != 4) {
- free(storage);
- return RL7A_TOO_SHORT;
- }
- read_count = fread((void *) &trailer_count, sizeof(unsigned int), 1, fp);
- if (read_count != 1) {
- free(storage);
- return RL7A_TOO_SHORT;
- }
- if (memcmp((void *) trailer_first4, (void *) L7A_FIRST_4, 4) != 0
- || el_count != trailer_count) {
- free(storage);
- return RL7A_BAD_TRAILER;
- }
- if (fclose(fp) != 0) {
- free(storage);
- return RL7A_CLOSE_FAIL;
- }
- ad->arr = storage;
- ad->len = el_count;
- ad->cap = el_count;
- return RL7A_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement