File: loadppm.c

package info (click to toggle)
mesa 7.7.1-6
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 98,864 kB
  • ctags: 137,548
  • sloc: ansic: 736,522; cpp: 32,250; xml: 11,831; python: 10,446; asm: 8,599; makefile: 4,731; sh: 3,708; yacc: 2,226; lex: 495
file content (72 lines) | stat: -rw-r--r-- 1,340 bytes parent folder | download | duplicates (3)
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

typedef struct {
    size_t sizeX, sizeY;
    GLubyte *data;
} PPMImage;

static PPMImage *LoadPPM(const char *filename)
{
    char buff[16];
    PPMImage *result;
    FILE *fp;
    int maxval;

    fp = fopen(filename, "rb");
    if (!fp)
    {
	fprintf(stderr, "Unable to open file `%s'\n", filename);
	exit(1);
    }

    if (!fgets(buff, sizeof(buff), fp))
    {
	perror(filename);
	exit(1);
    }

    if (buff[0] != 'P' || buff[1] != '6')
    {
	fprintf(stderr, "Invalid image format (must be `P6')\n");
	exit(1);
    }

    result = (PPMImage *) malloc(sizeof(PPMImage));
    if (!result)
    {
	fprintf(stderr, "Unable to allocate memory\n");
	exit(1);
    }

    if (fscanf(fp, "%lu %lu", &result->sizeX, &result->sizeY) != 2)
    {
	fprintf(stderr, "Error loading image `%s'\n", filename);
	exit(1);
    }

    if (fscanf(fp, "%d", &maxval) != 1)
    {
	fprintf(stderr, "Error loading image `%s'\n", filename);
	exit(1);
    }

    while (fgetc(fp) != '\n')
	;

    result->data = (GLubyte *) malloc(3 * result->sizeX * result->sizeY);
    if (!result)
    {
	fprintf(stderr, "Unable to allocate memory\n");
	exit(1);
    }

    if (fread(result->data, 3 * result->sizeX, result->sizeY, fp) != result->sizeY)
    {
	fprintf(stderr, "Error loading image `%s'\n", filename);
	exit(1);
    }

    fclose(fp);

    return result;
}