Ian Jauslin
summaryrefslogtreecommitdiff
path: root/src/io.c
diff options
context:
space:
mode:
authorIan Jauslin <ian@jauslin.org>2022-05-27 16:09:17 -0400
committerIan Jauslin <ian@jauslin.org>2022-05-27 16:09:17 -0400
commit0cdb914b5764f692189ed2bc395e3b09ead758e4 (patch)
tree91fed5d86febab728add0425e2d501a7e3cb67a1 /src/io.c
parent6b96c2d9461d59662705da766d13318b3cb0da2d (diff)
savefile and initfile
Diffstat (limited to 'src/io.c')
-rw-r--r--src/io.c112
1 files changed, 112 insertions, 0 deletions
diff --git a/src/io.c b/src/io.c
new file mode 100644
index 0000000..5cdfc54
--- /dev/null
+++ b/src/io.c
@@ -0,0 +1,112 @@
+#include <stdbool.h>
+#include <stdlib.h>
+#include "io.h"
+#include "navier-stokes.h"
+
+// write final entry to file
+int write_u(_Complex double* u, int K1, int K2, FILE* file){
+ int kx,ky;
+
+ // do nothing if there is no file
+ if(file==NULL){
+ return 0;
+ }
+
+ for(kx=-K1;kx<=K1;kx++){
+ for (ky=-K2;ky<=K2;ky++){
+ fprintf(file,"%d %d % .15e % .15e\n",kx,ky,__real__ u[klookup(kx,ky,2*K1+1,2*K2+1)],__imag__ u[klookup(kx,ky,2*K1+1,2*K2+1)]);
+ }
+ }
+
+ return 0;
+}
+
+// read u from file
+int read_u(_Complex double* u, int K1, int K2, FILE* file){
+ int kx,ky;
+ double r,i;
+ char* line;
+ unsigned int len=256;
+ unsigned int pos=0;
+ char* line_realloc;
+ char c;
+ int ret;
+ unsigned int counter=0;
+ bool commented=false;
+
+ // error if there is no file (this should not happen)
+ if (file==NULL){
+ fprintf(stderr,"error reading u from file (this is a bug!)\n");
+ return -1;
+ }
+
+ // allocate line buffer
+ line=calloc(sizeof(char), len);
+
+ while(1){
+ c=fgetc(file);
+
+ // end of file
+ if (feof(file)){
+ break;
+ }
+
+ // newline: read line and reset buffer
+ if(c=='\n' || c=='\r'){
+ // increment line counter
+ counter++;
+
+ // read entry
+ // ignore empty lines
+ if(pos>0){
+ ret=sscanf(line, "%d %d %le %le", &kx, &ky, &r, &i);
+
+ // errors
+ if(ret!=4){
+ fprintf(stderr, "warning: line %d does not match the input format: '%s'\n", counter, line);
+ }
+ else{
+ if(kx>K1 || kx<-K1 || ky>K2 || ky<-K2){
+ fprintf(stderr, "warning: reading line %d: kx or ky out of bounds: %d,%d\n", counter, kx, ky);
+ }
+ else{
+ // set u
+ u[klookup(kx, ky, 2*K1+1, 2*K2+1)]=r+i*I;
+ }
+ }
+ }
+
+ // reset buffer
+ pos=0;
+ line[pos]='\0';
+ commented=false;
+ }
+ // comment: stop reading
+ else if (c=='#'){
+ commented=true;
+ }
+ // add to buffer (unless we are in a comment)
+ else if (!(commented)){
+ // check that there is room in buffer
+ if(pos==len){
+ // too short: reallocate
+ line_realloc=calloc(sizeof(char), 2*len);
+ for(pos=0;pos<len;pos++){
+ line_realloc[pos]=line[pos];
+ }
+ free(line);
+ line=line_realloc;
+ len=2*len;
+ }
+
+ // add c to line
+ line[pos]=c;
+ pos++;
+ line[pos]='\0';
+ }
+ }
+
+ free(line);
+
+ return 0;
+}