#include #include #include "readnums.h" static int *get_number_line(FILE *f) { int *nums; int size = 10, count = 0, num = 0, digits = 0; int ch; nums = (int*)malloc(sizeof(int) * size); while (1) { ch = fgetc(f); if ((ch == ' ') || (ch == '\r') || (ch == '\n') || (ch == EOF)) { if (digits != 0) { if (!num) { fprintf(stderr, "found a zero\n"); abort(); } if (count + 1 >= size) { int *new_nums; size *= 2; new_nums = (int*)malloc(sizeof(int) * size); memcpy(new_nums, nums, sizeof(int) * (count + 1)); nums = new_nums; } nums[count] = num; count++; digits = 0; num = 0; } } if (ch == '\r') { ch = fgetc(f); if (ch != '\n') { fprintf(stderr, "expected a newline after a carriage return\n"); abort(); } break; } else if (ch == '\n') break; else if (ch == EOF) { if (!count) return NULL; break; } else if (ch == ' ') { /* ignore space */ } else if ((ch >= '0') && (ch <= '9')) { int new_num; digits++; new_num = (num * 10) + (ch - '0'); if ((new_num / 10) != num) { fprintf(stderr, "number too large: %d...\n", num); abort(); } num = new_num; } else { fprintf(stderr, "not a space, newline, return, or digit: %c\n", ch); abort(); } } if (!count) { fprintf(stderr, "found an empty line\n"); abort(); } else { nums[count] = 0; return nums; } } int **get_number_lines(FILE *f) { int **numss, *nums; int size = 10, count = 0; numss = (int**)malloc(sizeof(int*) * size); while (1) { nums = get_number_line(f); if (!nums) break; if (count + 1 >= size) { int **new_numss; size *= 2; new_numss = (int**)malloc(sizeof(int*) * size); memcpy(new_numss, numss, sizeof(int*) * (count + 1)); numss = new_numss; } numss[count] = nums; count++; } numss[count] = NULL; return numss; }