Merge pull request #113 from gitter-badger/gitter-badge
[sddekit.git] / src / out_file.c
blobe523709989bc417896faae3354bef15ed1b30bfc
1 /* copyright 2016 Apache 2 sddekit authors */
3 #include "sddekit.h"
5 /* write data to file */
7 typedef struct file_data {
8 sd_out out_if;
9 sd_out_file file_if;
10 FILE *fd;
11 bool isstd;
12 } file_data;
14 static sd_stat
15 file_apply(sd_out *out, double t,
16 uint32_t nx, double * restrict x,
17 uint32_t nc, double * restrict c)
19 uint32_t i;
20 file_data *d = out->ptr;
21 fprintf(d->fd, "%f %d ", t, nx);
22 for (i=0; i<nx; i++)
23 fprintf(d->fd, "%f ", x[i]);
24 fprintf(d->fd, "%d ", nc);
25 for (i=0; i<nc; i++)
26 fprintf(d->fd, "%f ", c[i]);
27 fprintf(d->fd, "\n");
28 return SD_CONT;
31 static void
32 file_free(sd_out *out)
34 file_data *d = out->ptr;
35 if (!(d->isstd))
36 fclose(d->fd);
37 sd_free(d);
40 static bool
41 file_is_std(sd_out_file *file)
43 return ((file_data*)file->ptr)->isstd;
46 static sd_out *
47 out_from_file(sd_out_file *file)
49 return &(((file_data*)file->ptr)->out_if);
52 static FILE *
53 file_get_fd(sd_out_file *file)
55 return ((file_data*)file->ptr)->fd;
58 static sd_out
59 file_out_defaults = { .free = &file_free, .apply = &file_apply };
61 static sd_out_file
62 file_defaults = { .out = &out_from_file,.is_std = &file_is_std,.get_fd = &file_get_fd };
64 static sd_out_file *
65 sd_out_file_new(FILE *file, bool is_std)
67 file_data *d;
68 d = sd_malloc (sizeof(file_data));
69 if (d == NULL)
71 sd_err("alloc out file failed.");
72 return NULL;
75 file_data zero = { 0 };
76 *d = zero;
78 d->fd = file;
79 d->isstd = is_std;
80 d->file_if = file_defaults;
81 d->out_if = file_out_defaults;
82 d->file_if.ptr = d->out_if.ptr = d;
83 return &(d->file_if);
86 sd_out_file *
87 sd_out_file_new_from_name(char *fname)
89 FILE *file;
90 if ((file = fopen(fname, "w"))==NULL)
92 sd_err("unable to open file for writing.");
93 return NULL;
95 return sd_out_file_new(file, false);
98 sd_out_file *
99 sd_out_file_new_from_std(FILE *std)
101 return sd_out_file_new(std, true);