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
|
/*
* Copyright 2008 Johannes Hofmann <Johannes.Hofmann@gmx.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*/
/* This code is based on Fl_PNM_Image.cxx from fltk (http://www.fltk.org)
*/
#include <string.h>
#include "pnm.h"
int
readPnmHeader(FILE *fp, struct pnm *h) {
char line[1024];
char *lineptr;
memset(h, 0, sizeof(struct pnm));
lineptr = fgets(line, sizeof(line), fp);
if (!lineptr) {
fprintf(stderr, "premature end of pnm file\n");
return 1;
}
lineptr ++;
h->format = atoi(lineptr);
while (isdigit(*lineptr)) lineptr ++;
if (h->format == 7) lineptr = (char *)"";
while (lineptr != NULL && h->width == 0) {
if (*lineptr == '\0' || *lineptr == '#') {
lineptr = fgets(line, sizeof(line), fp);
} else if (isdigit(*lineptr)) {
h->width = strtol(lineptr, &lineptr, 10);
} else lineptr ++;
}
while (lineptr != NULL && h->height == 0) {
if (*lineptr == '\0' || *lineptr == '#') {
lineptr = fgets(line, sizeof(line), fp);
} else if (isdigit(*lineptr)) {
h->height = strtol(lineptr, &lineptr, 10);
} else lineptr ++;
}
if (h->format != 1 && h->format != 4) {
h->maxval = 0;
while (lineptr != NULL && h->maxval == 0) {
if (*lineptr == '\0' || *lineptr == '#') {
lineptr = fgets(line, sizeof(line), fp);
} else if (isdigit(*lineptr)) {
h->maxval = strtol(lineptr, &lineptr, 10);
} else lineptr ++;
}
} else {
h->maxval = 1;
}
return 0;
}
int
writePnmHeader(FILE *fp, const struct pnm *h) {
fprintf(fp, "P%d\n", h->format);
fprintf(fp, "%d %d\n", h->width, h->height);
fprintf(fp, "%d\n", h->maxval);
return 0;
}
|