-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathppm.c
69 lines (55 loc) · 1.51 KB
/
ppm.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
// ppm.c
// Řešení IJC-DU1, příklad b), 25.2. 2023
// Autor: Jakub Antonín Štigler, FIT
// Přeloženo: clang 15.0.7
// C standard: C11
// Funguje i s gcc 12.2.1 (make CC=gcc)
#include "ppm.h"
#include <stdio.h> // FILE, fscnaf, fopen, fclose, size_t, fread
#include <ctype.h> // isspace
#include <stdlib.h> // free, malloc
#include "error.h" // warning
_Bool _ppm_read_header(FILE *in, unsigned *w, unsigned *h) {
char c;
if (fscanf(in, "P6 %u %u 255%c", w, h, &c) != 3) {
warning("_ppm_read_header: Invalid/unsupported file header");
return 0;
}
if (!isspace(c)) {
warning(
"_ppm_read_hreader: Expected whitespace after header, found '%c'",
c
);
return 0;
}
return 1;
}
struct ppm *ppm_read(const char *filename) {
FILE *in = fopen(filename, "rb");
if (!in) {
warning("ppm_read: Failed to open file '%s'", filename);
return NULL;
}
unsigned w, h;
if (!_ppm_read_header(in, &w, &h))
return NULL;
if (w > PPM_MAX_WH || h > PPM_MAX_WH) {
warning("ppm_read: Image is too large");
return NULL;
}
size_t pcount = w * h;
struct ppm *p = malloc(sizeof(unsigned) * 2 + 3 * pcount);
p->xsize = w;
p->ysize = h;
if (fread(p->data, 3, pcount, in) != pcount) {
fclose(in);
ppm_free(p);
warning("ppm_read: File is too short");
return NULL;
}
fclose(in);
return p;
}
void ppm_free(struct ppm *p) {
free(p);
}