Friday, June 30, 2017

t1.c

#include<intarr.h>
#include<stdio.h>

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename )
{
  unsigned int length = ia->len;
  FILE* f = fopen(filename, "w");
  if(f == NULL){
    return 1;
  }
  // write the length header
  int hdr[1];
  hdr[0] = ia->len;

  if( fwrite(hdr, sizeof(intarr_t), 1, f) != 1){
    return 1;
  }

  if(fwrite(ia->data, sizeof(intarr_t),length, f) != length){
    return 1;
  }
  fclose(f);
  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename )
{
  FILE* f = fopen(filename, "r");
  if(f == NULL){
    return NULL;
  }
  int hdr[1];
  if( fread(hdr, sizeof(intarr_t), 1, f) != 1){
    return 1;
  }

  intarr_t ia;
  ia->len = hdr[0];
  ia->data = malloc((ia->len)*sizeof(int));
  if(ia->len != 0){
    if(ia->data == NULL){
      return NULL;
    }
  }

  if(fread(ia->data, sizeof(intarr_t),length, f) != length){
    return NULL;
  }
  fclose(f);
  return ia;
}

No comments:

Post a Comment