/* * METRIC --- Mode expansion modeling in integrated optics / photonics * http://metric.computational-photonics.eu/ */ /* * inout.cpp * Basic file input / output functions */ #include #include /* write, read char, int, double - values from/to files, values must appear on separate lines, maybe divided by comment lines, starting with '#' */ /* error message */ void inouterror(const char *m) { fprintf(stderr, "\ninout: %s.\n", m); exit(1); } /* write comment */ void comment(const char *c, FILE *dat) { fprintf(dat, "## %s ##\n", c); return; } /* write character */ void fputchar(char c, FILE *dat) { fprintf(dat, "%c\n", c); return; } /* write int */ void fputint(int i, FILE *dat) { fprintf(dat, "%d\n", i); return; } /* write double */ void fputdouble(double d, FILE *dat) { fprintf(dat, "%.15g\n", d); return; } /* input space */ #define ILENGTH 256 char Line[ILENGTH]; /* character input from file dat */ char fgetchar(FILE *dat) { char c; while(fgets(Line, ILENGTH-1, dat) != NULL) { c = Line[0]; if(c != '#') return c; } c = ' '; return c; } /* integer input from file dat */ int fgetint(FILE *dat) { char c; int i, r; while(fgets(Line, ILENGTH-1, dat) != NULL) { c = Line[0]; if(c != '#') { r = sscanf(Line, "%d", &i); if(r != EOF) return i; else return 0; } } return 0; } /* double input from file dat */ double fgetdouble(FILE *dat) { char c; int r; double d; while(fgets(Line, ILENGTH-1, dat) != NULL) { c = Line[0]; if(c != '#') { r = sscanf(Line, "%lg", &d); if(r != EOF) return d; else return 0.0; } } return 0.0; } /* ----------------------------------------------------------- */ /* digits of integer numbers 0<=i<=999 */ char dig1000(int i) { return '0'+i/1000; } char dig100(int i) { return '0'+(i-(i/1000)*1000)/100; } char dig10(int i) { return '0'+(i-(i/100)*100)/10; } char dig1(int i) { return '0'+i%10; } /* ----------------------------------------------------------- */ /* append double value to file name.xf; create if necessary */ void apptoxf(const char *name, double x) { FILE *f; int l; char n[20]; l=0; while(l<=15 && name[l] != 0) {n[l] = name[l]; ++l;} n[l] = '.'; ++l; n[l] = 'x'; ++l; n[l] = 'f'; ++l; n[l] = 0; f = fopen(n, "a+"); fprintf(f, "%.15g\n", x); fclose(f); return; } /* append (x, y)-pair to file name.xyf; create if necessary */ void apptoxyf(const char *name, double x, double y) { FILE *f; int l; char n[20]; l=0; while(l<=15 && name[l] != 0) {n[l] = name[l]; ++l;} n[l] = '.'; ++l; n[l] = 'x'; ++l; n[l] = 'y'; ++l; n[l] = 'f'; ++l; n[l] = 0; f = fopen(n, "a+"); fprintf(f, "%.15g %.15g\n", x, y); fclose(f); return; } /* append (x, y1, y2)-triple to file name.xyf; create if necessary */ void apptoxyf(const char *name, double x, double y1, double y2) { FILE *f; int l; char n[20]; l=0; while(l<=15 && name[l] != 0) {n[l] = name[l]; ++l;} n[l] = '.'; ++l; n[l] = 'x'; ++l; n[l] = 'y'; ++l; n[l] = 'f'; ++l; n[l] = 0; f = fopen(n, "a+"); fprintf(f, "%.15g %.15g %.15g\n", x, y1, y2); fclose(f); return; }