Fleeting thoughts

nummax - find the biggest number

by Johannes Martinsson

I live a lot in the terminal, and I often do data crunching. I’ve found the following utility quite useful; it reads numbers on standard in and returns the biggest number seen once there is nothing left on standard in.

All numbers are assumed to be floating point numbers. There is no error handling currently, 😐 this is mostly just because I’ve found that it works good enough at the moment. ☔

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
	char *buf = malloc(1024);
	double current = 0;
	double max = 0;

	while (fgets(buf, 1024, stdin) != NULL) {
		current = atof(buf);
		if (current > max) {
			max = current;
		}
	}
	printf("%10.10f\n", max);
	free(buf);
	return 0;
}

Example run

% (repeat 10; print $RANDOM) | nummax
30487.0000000000