fbvis: more keys for moving to the next/previous file
[fbvis.git] / ppm.c
blobc9d8840b278cc43ed8474047c0992e30dfcf82b2
1 #include <ctype.h>
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
10 static int nextchar(int fd)
12 unsigned char b[4] = {0};
13 read(fd, b, 1);
14 return b[0];
17 static int cutint(int fd)
19 int c;
20 int n = 0;
21 do {
22 c = nextchar(fd);
23 } while (isspace(c));
24 while (isdigit(c)) {
25 n = n * 10 + c - '0';
26 c = nextchar(fd);
28 return n;
31 char *ppm_load(char *path, int *h, int *w)
33 char *d;
34 int fd = open(path, O_RDONLY);
35 if (fd < 0 || nextchar(fd) != 'P' || nextchar(fd) != '6')
36 return NULL;
37 *w = cutint(fd); /* image width */
38 *h = cutint(fd); /* image height */
39 cutint(fd); /* max color val */
41 d = malloc(*h * *w * 3);
42 read(fd, d, *h * *w * 3);
43 close(fd);
44 return d;
47 void ppm_save(char *path, char *s, int h, int w)
49 char sig[128];
50 int fd;
51 sprintf(sig, "P6\n%d %d\n255\n", w, h);
52 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0600);
53 write(fd, sig, strlen(sig));
54 write(fd, s, h * w * 3);
55 close(fd);