-
Notifications
You must be signed in to change notification settings - Fork 0
/
importdata.c
81 lines (64 loc) · 2.18 KB
/
importdata.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
/*----------------------------------------------------------------------------*/
/* importdata.c */
/* Author: Godwin Duan */
/*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "importdata.h"
int import_data(char *filename, Simulation *sim)
{
FILE *fp;
char string_sim_type[7];
int i;
assert(filename != NULL);
fp = fopen(filename, "r");
if (fp == NULL)
{
fprintf(stderr, "Failed to open input file.\n");
return 1;
}
if (strrchr(filename, '.') != NULL)
*strrchr(filename, '.') = '\0';
strcpy(sim->filename, filename);
fscanf(fp, "%6s\n", string_sim_type);
if (strcasecmp("String", string_sim_type) == 0)
sim->sim_type = STRING;
else if (strcasecmp("Spring", string_sim_type) == 0)
sim->sim_type = SPRING;
else
{
fprintf(stderr, "Simulation type must be either string or spring.\n");
return 1;
}
/* Scan in tension if it's a string simulation */
if (sim->sim_type == STRING)
fscanf(fp, "%lf", &(sim->tension));
fscanf(fp, "%d", &(sim->num_beads));
/* Allocate memory for beads and connections */
sim->beads = calloc(sim->num_beads, sizeof(Bead));
if (sim->beads == NULL)
{
fprintf(stderr, "Failed to allocate memory for beads.\n");
return 1;
}
sim->connections = calloc(sim->num_beads + 1, sizeof(double));
if (sim->connections == NULL)
{
fprintf(stderr, "Failed to allocate memory for connections.\n");
return 1;
}
for (i = 0; i < sim->num_beads; i++)
{
fscanf(fp, "%lf", &(sim->connections[i]));
fscanf(fp, "%lf %lf %lf", &(sim->beads[i].mass),
&(sim->beads[i].x0),
&(sim->beads[i].v0));
}
/* There's one more connection than bead; scan that in */
fscanf(fp, "%lf", &(sim->connections[sim->num_beads]));
fclose(fp);
printf("Finished importing data from %s\n\n", filename);
return 0;
}