-
Notifications
You must be signed in to change notification settings - Fork 1
/
store.c
149 lines (114 loc) · 2.92 KB
/
store.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/* =====[ store.c ]=========================================================
Description: Store varible for pcalc
Revisions:
REV DATE BY DESCRIPTION
---- -------- ---------- --------------------------------------
0.00 21/9/98 Peter Glen Initial version.
======================================================================= */
/* -------- System includes: -------------------------------------------- */
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
/* -------- Includes: --------------------------------------------------- */
#include "store.h"
#include "symbol.h"
#include "hocdecl.h" /* data declarations, function prototypes */
/* -------- Implementation: ---------------------------------------------- */
static char work_str[128];
int store(char *file, char *name, double var)
{
FILE *fp = NULL;
int found = FALSE;
int namelen;
char tmp[18];
Symbol *ms = lookup_sym("DEBUG_STORE");
if(ms && ms->u.val)
printf("Storing: %s\n", name);
strncpy(tmp, name, 16); // cutted local copy
tmp[16] = '\0';
namelen = strlen(tmp);
fp = fopen(file, "r+");
if(!fp)
{
fp = fopen(file, "w+");
if(ms && ms->u.val)
printf("Creating out file\n");
}
if(!fp)
{
if(ms && ms->u.val)
printf("Could not create file.\n");
return(0);
}
*work_str = 0;
while(TRUE)
{
long pos = ftell(fp);
if(!fgets(work_str, sizeof(work_str), fp))
{
break;
}
//printf("fgets got: %s\n", work_str);
if(*work_str == 0)
{
// printf("empty string\n");
break;
}
if(!strncmp(work_str, tmp, namelen))
{
fseek(fp, pos, SEEK_SET);
found = TRUE;
break;
}
if(feof(fp))
break;
if(ferror(fp))
break;
}
sprintf(work_str, "%-16s = %-16e\n", tmp, var);
fputs(work_str, fp);
fclose(fp);
return(1);
}
int restore(char *file, char *name, double *var)
{
FILE *fp = NULL;
int found = FALSE;
int namelen;
char tmp[18];
Symbol *ms = lookup_sym("DEBUG_STORE");
if(ms && ms->u.val )
printf("Restoring: %s\n", name);
strncpy(tmp, name, 16); // cutted local copy
tmp[16] = '\0';
namelen = strlen(tmp);
*var = 0.0;
fp = fopen(file, "rt+");
if(!fp)
return(0);
while(TRUE)
{
if(!fgets(work_str, sizeof(work_str), fp))
break;
if(!strncmp(work_str, tmp, namelen))
{
found = TRUE;
break;
}
if(feof(fp))
break;
if(ferror(fp))
break;
}
if(found)
{
float dd;
sscanf(work_str, "%*s = %e", &dd);
*var = dd;
}
fclose(fp);
return(1);
}
/* EOF */