-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileio.c
81 lines (74 loc) · 2.63 KB
/
fileio.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Writes state of the simulation to given file in form
* index of object; positions; velocity;
*
* Different dimensions are separated with comma.
*
* fp: Pointer to output file
* time: Double giving current time
* pos: Double array containing positions to be written
* vel: Double array containing velocities to be written
* nBodies: Number of bodies in simulation
* dimensions: Number of dimensions
*
*/
void dumpSim(FILE *fp, double time, double *pos, double *vel, int nBodies, int dimensions){
for(int i=0; i<nBodies; i++){
// index of body
fprintf(fp, "%i;\t%e;\t", i, time);
// position
for(int j=0; j<dimensions; j++){
fprintf(fp, "%.15e", pos[i*dimensions+j]);
if (j<dimensions-1){
fprintf(fp, ",\t");
} else {
fprintf(fp, ";\t");
}
}
// velocity
for(int j=0; j<dimensions; j++){
fprintf(fp, "%.15e", vel[i*dimensions+j]);
if (j<dimensions-1){
fprintf(fp, ",\t");
} else {
fprintf(fp, ";\n");
}
}
}
}
/*
* Reads initial conditions from file, each row containing data for one body,
* first three rows representing position, next three velocities and last one mass,
* and writes them into the given arrays. Numbers in scientific notation separated
* by space.
*
* Empty lines and lines starting with # are ignored.
*
* fp: File pointer to input file
* pos: Double array that is big enough for the data (3*nBodies), will
* contain the positions of bodies
* vel: Double array that is big enough for the data (3*nBodies), will
* contain the velocities of bodies
* mass: Double array that is big enough for the data (nBodies), will
* contain the masses of bodies
*
*/
void readInitialConditions(FILE *fp, double *pos, double *vel, double *mass){
size_t maxLinelength = 256;
char *lineBuffer = (char *)malloc(maxLinelength*sizeof(char));
int index = 0;
while (getline(&lineBuffer, &maxLinelength, fp) != -1){
// skip empty lines and lines starting with #
if (strlen(lineBuffer) > 1 && lineBuffer[0] != '#'){
sscanf(lineBuffer, "%lf %lf %lf %lf %lf %lf %lf",
&pos[index*3], &pos[index*3+1], &pos[index*3+2],
&vel[index*3], &vel[index*3+1], &vel[index*3+2],
&mass[index]);
index++;
}
}
free(lineBuffer);
}