Take scanf out of puzzles.cgi

This commit is contained in:
Neale Pickett 2010-09-16 12:20:44 -06:00
parent 04d3c2c66c
commit 487893c314
1 changed files with 47 additions and 27 deletions

View File

@ -25,23 +25,53 @@ struct {
} points_by_cat[PUZZLES_MAX];
int ncats = 0;
void
read_points_by_cat()
size_t
read_until_char(FILE *f, char *buf, size_t buflen, char delim)
{
size_t i = 0;
while (1) {
int c = fgetc(f);
if ((EOF == c) || delim == c) {
if (buf) {
buf[i] = '\0';
}
return i;
}
if (i + 1 < buflen) {
buf[i] = c;
}
i += 1;
}
}
int
main(int argc, char *argv[])
{
int i;
DIR *srv;
if (-1 == cgi_init(argv)) {
return 0;
}
{
FILE *f = fopen(srv_path("puzzler.db"), "r");
char cat[CAT_MAX];
char points_str[11];
long points;
int i;
if (! f) {
return;
}
while (f && (! feof(f))) {
read_until_char(f, NULL, 0, ' ');
read_until_char(f, cat, sizeof(cat), ' ');
read_until_char(f, points_str, sizeof(points_str), '\n');
points = atol(points_str);
printf("%s %ld\n", cat, points);
while (1) {
/* XXX: tokenize like cgi_item */
if (2 != fscanf(f, "%*s %s %ld\n", cat, &points)) {
break;
}
for (i = 0; i < ncats; i += 1) {
if (0 == strcmp(cat, points_by_cat[i].cat)) break;
}
@ -57,20 +87,10 @@ read_points_by_cat()
points_by_cat[i].points = points;
}
}
if (f) fclose(f);
}
int
main(int argc, char *argv[])
{
int i;
DIR *srv;
if (-1 == cgi_init(argv)) {
return 0;
}
read_points_by_cat();
srv = opendir(srv_path("packages"));
if (NULL == srv) {
cgi_error("Cannot opendir(\"/srv\")");
@ -137,7 +157,7 @@ main(int argc, char *argv[])
printf(" <dt>%s</dt>\n", cat);
printf(" <dd>\n");
for (i = 0; i < ncatpoints; i += 1) {
printf(" <a href=\"/puzzles/%s/%d\">%d</a>\n",
printf(" <a href=\"/puzzles/%s/%ld\">%ld</a>\n",
cat, catpoints[i], catpoints[i]);
if (catpoints[i] > maxpoints) break;
}