-
Notifications
You must be signed in to change notification settings - Fork 1
/
punto.c
138 lines (121 loc) · 2.83 KB
/
punto.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
#include <stdio.h>
#include <string.h>
#include "real.h"
#include "inc/def.h"
#include "co/err.h"
#define FMT_IN CO_REAL_IN
#define FMT_OUT CO_REAL_OUT
#define SIZE (MAX_STRING_SIZE)
int
punto_fwrite(int n, const real * queue[], /**/ FILE * f)
{
int i, r;
const real **q;
for (i = 0; i < n; i++) {
q = queue;
while (*q != NULL) {
r = fprintf(f, FMT_OUT, (*q)[i]);
q++;
if (r < 0)
ERR(CO_IO, "fail to write");
if (*q != NULL)
fputc(' ', f);
else {
fputc('\n', f);
break;
}
}
}
return CO_OK;
}
int
punto_write(int n, const real * queue[], /**/ const char *path)
{
FILE *f;
if ((f = fopen(path, "w")) == NULL)
ERR(CO_IO, "fail to open '%s'", path);
if (punto_fwrite(n, queue, f) != CO_OK)
ERR(CO_IO, "fail to write to '%s", path);
if (fclose(f) != 0)
ERR(CO_IO, "fail to close '%s'", path);
return CO_OK;
}
int
punto_fappend(int n, const real * queue[], /**/ FILE * f)
{
int i, r;
const real **q;
for (i = 0; i < n; i++) {
q = queue;
for (;;) {
r = fprintf(f, FMT_OUT, (*q)[i]);
q++;
if (r < 0)
ERR(CO_IO, "fail to write");
if (*q != NULL)
fputc(' ', f);
else {
fputc('\n', f);
break;
}
}
}
fputc('\n', f);
return CO_OK;
}
int
punto_append(int n, const real * queue[], /**/ const char *path)
{
FILE *f;
if ((f = fopen(path, "a")) == NULL)
ERR(CO_IO, "fail to open '%s'", path);
if (punto_fappend(n, queue, f) != CO_OK)
ERR(CO_IO, "fail to write to '%s", path);
if (fclose(f) != 0)
ERR(CO_IO, "fail to close '%s'", path);
return CO_OK;
}
enum { OK, FAIL };
static int
read(char *s, int i, real * q[])
{
const char delim[] = " \t";
char *tok;
for (;; s = NULL) {
if (*q == NULL)
break;
if ((tok = strtok(s, delim)) == NULL)
return FAIL;
if (sscanf(tok, FMT_IN, &(*q)[i]) != 1)
return FAIL;
q++;
}
return OK;
}
static int
blank(const char *s)
{
char c;
while ((c = *s++) != '\0')
if (c != ' ' && c != '\t' && c != '\n')
return 0;
return 1;
}
int
punto_read(const char *path, /**/ int *pn, real * queue[])
{
FILE *f;
int n;
char s[SIZE];
if ((f = fopen(path, "r")) == NULL)
ERR(CO_IO, "fail to open '%s'", path);
n = 0;
while (fgets(s, SIZE, f) != NULL && !blank(s)) {
if (read(s, n++, queue) != OK)
ERR(CO_IO, "wrong line '%s' in file '%s'", s, path);
}
if (fclose(f) != 0)
ERR(CO_IO, "fail to close '%s'", path);
*pn = n;
return CO_OK;
}