/* File: sorting.c Support routines for sorting binary files which contain arrays of integers. */ #include #include #include #include "sorting.h" /* Get file size of open stream returns -1 as error */ int fsize(FILE *ifile) { int r, size ; struct stat buf ; if (ifile == NULL) return -1 ; r = fstat(ifile->_file, &buf) ; if (r != 0) return -1 ; return buf.st_size ; } /* Read an array of integers stored in binary file Returns number of items read or -1 for error. If no items read, *A is not changed. */ index readarray(char *filename, data **A_ptr) { FILE *ifile ; index n ; int r, size ; ifile = fopen(filename, "rb") ; if (ifile == NULL) return -1 ; size = fsize(ifile) ; if (size < 0) return -1 ; n = size/sizeof(data) ; if (n == 0) return 0 ; *A_ptr = (data *) malloc(n*sizeof(data)) ; r = fread(*A_ptr, sizeof(data), n, ifile) ; fclose(ifile) ; if (n != r) { fprintf(stderr, "Bad file format\n") ; exit(-1) ; } return n ; } void printarray(data A[], index n) { index i ; for (i = 0 ; i < n ; i++) { printf("%12d ", A[i]) ; if (i % 5 == 4) printf("\n") ; } } int checkarray(data A[], index n) { index i ; for (i = 0 ; i < n-1 ; i++) { if (A[i] > A[i+1]) return 0 ; } return 1 ; }