shear_flux.c (1187B)
1 #include <err.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <err.h> 6 7 #include "arg.h" 8 9 char *argv0; 10 11 static void 12 usage(void) 13 { 14 fprintf(stderr, "usage: %s " 15 "[-v] " 16 "[-h] " 17 "[file ...] " 18 "\n", argv0); 19 exit(1); 20 } 21 22 /* input format: positions<TAB>shear_velocities */ 23 static double 24 find_flux(FILE *f) 25 { 26 int i = 0; 27 double pos, vel, pos_prev, vel_prev, flux = 0.0; 28 29 while (fscanf(f, "%lf\t%lf%*[^\n]", &pos, &vel) == 2) { 30 if (i++ > 0) 31 flux += (vel + vel_prev) / 2.0 * (pos - pos_prev); 32 pos_prev = pos; 33 vel_prev = vel; 34 } 35 if (i == 1) 36 err(1, "could not read input data"); 37 38 return flux; 39 } 40 41 int 42 main(int argc, char *argv[]) 43 { 44 int i; 45 FILE *fp; 46 47 #ifdef __OpenBSD__ 48 if (pledge("stdio rpath", NULL) == -1) 49 err(2, "pledge failed"); 50 #endif 51 52 ARGBEGIN { 53 case 'h': 54 usage(); 55 break; 56 case 'v': 57 printf("%s-"VERSION"\n", argv0); 58 return 0; 59 break; 60 default: 61 usage(); 62 } ARGEND; 63 64 if (argc > 0) { 65 for (i = 0; i < argc; i++) { 66 if (!(fp = fopen(argv[i], "r"))) 67 err(1, "fopen: %s", argv[i]); 68 69 printf("%.17g\n", find_flux(fp)); 70 fclose(fp); 71 } 72 } else 73 printf("%.17g\n", find_flux(stdin)); 74 75 return 0; 76 }