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