Created
April 18, 2019 04:29
-
-
Save marcomaggi/8530cf839f462078eb4e5f33255b6663 to your computer and use it in GitHub Desktop.
Toying with fscanf to read/write sampling data to/from a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* demo.c -- | |
Compile with: | |
gcc -Wall -std=c11 -lm -o demo demo.c | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
static char const * MY_PRIuSIZE; | |
typedef struct data_t data_t; | |
struct data_t { | |
size_t n; | |
double *t; | |
double *y; | |
}; | |
void | |
write_data (FILE * stream, data_t const * D) | |
{ | |
fprintf(stream, "N="); | |
fprintf(stream, MY_PRIuSIZE, D->n); | |
fprintf(stream, "\nt="); | |
for (size_t i=0; i<D->n; ++i) { | |
fprintf(stream, "%lf;", D->t[i]); | |
} | |
fprintf(stream,"\ny="); | |
for (size_t i=0; i<D->n; ++i) { | |
fprintf(stream, "%lf;", D->y[i]); | |
} | |
fprintf(stream,"\n"); | |
} | |
void | |
read_data (FILE * stream, data_t * D) | |
{ | |
fscanf(stream, "N="); | |
fscanf(stream, MY_PRIuSIZE, &(D->n)); | |
fscanf(stream, "\nt="); | |
for (size_t i=0; i<D->n; ++i) { | |
fscanf(stream, "%lf;", &(D->t[i])); | |
} | |
fscanf(stream,"\ny="); | |
for (size_t i=0; i<D->n; ++i) { | |
fscanf(stream, "%lf;", &(D->y[i])); | |
} | |
fscanf(stream,"\n"); | |
} | |
int | |
main (void) | |
{ | |
if (sizeof(unsigned int) == sizeof(size_t)) { | |
MY_PRIuSIZE = "%u"; | |
} else if (sizeof(unsigned long int) == sizeof(size_t)) { | |
MY_PRIuSIZE = "%lu"; | |
} else { | |
exit(EXIT_FAILURE); | |
} | |
{ | |
#undef NUM | |
#define NUM 32 | |
data_t D = { .n = NUM }; | |
double step = 0.01; | |
D.t = malloc(sizeof(double) * D.n); | |
D.y = malloc(sizeof(double) * D.n); | |
D.t[0] = 0.0; | |
D.y[0] = exp(D.t[0]); | |
for (size_t i=1; i<D.n; ++i) { | |
D.t[i] = step + D.t[i-1]; | |
D.y[i] = exp(D.t[i]); | |
} | |
{ | |
FILE * stream = fopen("data.txt", "w+"); | |
write_data(stream, &D); | |
fseek(stream, 0L, SEEK_SET); | |
read_data(stream, &D); | |
write_data(stderr, &D); | |
fclose(stream); | |
} | |
} | |
exit(EXIT_SUCCESS); | |
} | |
/* end of file */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment