[176] | 1 | /* |
---|
| 2 | * swift_context.c |
---|
| 3 | * |
---|
| 4 | * (c) 2009 Ionut Rosoiu <ionut.rosoiu@gmail.com> |
---|
| 5 | * |
---|
| 6 | */ |
---|
| 7 | |
---|
| 8 | #include <stdio.h> |
---|
| 9 | #include <stdlib.h> |
---|
| 10 | #include <time.h> |
---|
| 11 | |
---|
| 12 | #define SIZE 100 |
---|
| 13 | #define MAX 100 |
---|
| 14 | |
---|
| 15 | void read_array(char *filename, int **a, int *n) |
---|
| 16 | { |
---|
| 17 | FILE *f = fopen(filename, "rb"); |
---|
| 18 | int *arr, fsize, N, i; |
---|
| 19 | |
---|
| 20 | if (f == NULL) { |
---|
| 21 | fprintf(stderr, "Cannot open file: %s", filename); |
---|
| 22 | abort(); |
---|
| 23 | } |
---|
| 24 | |
---|
| 25 | *a = NULL; |
---|
| 26 | arr = NULL; |
---|
| 27 | |
---|
| 28 | fseek(f, 0, SEEK_END); |
---|
| 29 | fsize = (int) ftell(f); |
---|
| 30 | N = fsize / sizeof(int); |
---|
| 31 | fseek(f, 0, SEEK_SET); |
---|
| 32 | |
---|
| 33 | arr = (int *) malloc(N * sizeof(int)); |
---|
| 34 | |
---|
| 35 | if (!arr) { |
---|
| 36 | fprintf(stderr, "Out of memory"); |
---|
| 37 | abort(); |
---|
| 38 | } |
---|
| 39 | |
---|
| 40 | *a = arr; |
---|
| 41 | *n = N; |
---|
| 42 | |
---|
| 43 | for (i=0; i<N; i++) { |
---|
| 44 | if (!fread(&arr[i], sizeof(int), 1, f)) { |
---|
| 45 | fprintf(stderr, "Error reading item %d\n", i); |
---|
| 46 | } |
---|
| 47 | } |
---|
| 48 | } |
---|
| 49 | |
---|
| 50 | void write_array(char *filename, int N) |
---|
| 51 | { |
---|
| 52 | FILE *f = fopen(filename, "wb"); |
---|
| 53 | int i, val; |
---|
| 54 | |
---|
| 55 | if (f == NULL) { |
---|
| 56 | fprintf(stderr, "Cannot open file: %s", filename); |
---|
| 57 | abort(); |
---|
| 58 | } |
---|
| 59 | |
---|
| 60 | srand(time(NULL)); |
---|
| 61 | |
---|
| 62 | for (i=0; i<N; i++) { |
---|
| 63 | val = rand() % MAX; |
---|
| 64 | fwrite(&val, sizeof(int), 1, f); |
---|
| 65 | } |
---|
| 66 | |
---|
| 67 | fclose(f); |
---|
| 68 | } |
---|
| 69 | |
---|
| 70 | void free_array(int *a) |
---|
| 71 | { |
---|
| 72 | free(a); |
---|
| 73 | } |
---|
| 74 | |
---|
| 75 | void print_array(int *a, int n) |
---|
| 76 | { |
---|
| 77 | int i = 0; |
---|
| 78 | for (i=0; i<n-1; i++) { |
---|
| 79 | printf ("%d.%d\n", i, a[i]); |
---|
| 80 | } |
---|
| 81 | printf("\n"); |
---|
| 82 | } |
---|
| 83 | |
---|
| 84 | void check_array(int *a, int n) |
---|
| 85 | { |
---|
| 86 | int i = 0; |
---|
| 87 | for (i=0; i<n-1; i++) { |
---|
| 88 | if (a[i] > a[i+1]) { |
---|
| 89 | fprintf(stderr, "Invalid array: at pos %d, elements %d %d", i, a[i], a[i+1]); |
---|
| 90 | abort(); |
---|
| 91 | } |
---|
| 92 | } |
---|
| 93 | } |
---|