summaryrefslogtreecommitdiff
path: root/src/pnm.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/pnm.c')
-rw-r--r--src/pnm.c67
1 files changed, 67 insertions, 0 deletions
diff --git a/src/pnm.c b/src/pnm.c
new file mode 100644
index 0000000..b2fa3c8
--- /dev/null
+++ b/src/pnm.c
@@ -0,0 +1,67 @@
+#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;
+}
+