/* Averages multiple columns of numbers from a text file. */ /* Copyright (C) 2001 Finnegan Southey */ /* This work is licensed under the Gnu General Public License (see gpl.txt). */ #include #include int main(int argc, char **argv) { double value, *sums; int numCols, colCount, rowCount; FILE *in; char buffer[10000]; if (argc < 2) { fprintf(stderr, "Usage: %s <# cols> [ file ]\n", argv[0]); exit(1); } if (sscanf(argv[1], "%d", &numCols) != 1) { fprintf(stderr, "Usage: %s <# cols> [ file ]\n", argv[0]); exit(1); } if (argc == 3) { in = fopen(argv[2], "r"); if (in == NULL) { fprintf(stderr, "Error opening input file: %s\n", argv[2]); exit(1); } } else in = stdin; sums = calloc(numCols, sizeof(double)); rowCount = 0; while (!feof(in)) { rowCount++; for (colCount = 0; colCount < numCols; colCount++) { if (fscanf(in, " %lf ", &value) != 1) { fgets(buffer, 10000, in); // fprintf(stderr, "Skipped: %s\n", buffer); if (colCount == 0) { rowCount--; break; } else { printf("Incomplete line.\n"); exit(1); } } sums[colCount] += value; } } if (argc == 3) fclose(in); /* printf("%-7.5g", sums[0]); for (colCount = 1; colCount < numCols; colCount++) { printf("\t%-7.5g", sums[colCount]); } printf("\n"); */ printf("%-7.5g", sums[0] / rowCount); for (colCount = 1; colCount < numCols; colCount++) { printf("\t%-7.5g", sums[colCount] / rowCount); } printf("\n"); return 0; }