Project

General

Profile

Statistics
| Revision:

root / proj / src / xpm_utils.c @ 198

History | View | Annotate | Download (1.36 KB)

1 182 up20180642
#ifdef LCOM_MACRO
2
    #include <lcom/lcf.h>
3
#endif
4
5
#include "xpm_utils.h"
6
7
#include <stdio.h>
8
#include <stdlib.h>
9
#include <string.h>
10
11
void xpm_save_as_xpm2(char **p, const char *s){
12
    FILE *f = fopen(s, "w");
13
    int w, h, num_colors, chars_per_pixel;
14
    sscanf(p[0], "%d %d %d %d", &w, &h, &num_colors, &chars_per_pixel);
15
    for(int i = 0; i < 1+num_colors+h; ++i){
16
        fprintf(f, "%s\n", p[i]);
17
    }
18
    fclose(f); f = NULL;
19
}
20
21
char** xpm_load_xpm2(const char *fpath){
22
    FILE *f = fopen(fpath, "r");
23
    if(f == NULL) return NULL;
24 192 up20180642
    size_t len = 1024; char *line_buf = malloc(len*sizeof(char));
25 182 up20180642
    int sz;
26
27
    char **ret = NULL;
28
29
    int w, h, num_colors, chars_per_pixel;
30
31
    sz = getline(&line_buf, &len, f);{
32
        sscanf(line_buf, "%d %d %d %d", &w, &h, &num_colors, &chars_per_pixel);
33
        ret = malloc((1+num_colors+h)*sizeof(char*));
34
    }
35 183 up20180642
    ret[0] = malloc((sz+1)*sizeof(char)); if(ret[0] == NULL){ free(ret); return NULL; }
36 182 up20180642
    strcpy(ret[0], line_buf);
37 183 up20180642
38 182 up20180642
    for(int i = 1; i < 1+num_colors+h; ++i){
39
        sz = getline(&line_buf, &len, f);
40
        ret[i] = malloc((sz+1)*sizeof(char));
41 183 up20180642
        if(ret[i] == NULL){
42
            for(int j = 0; j < i; ++j)
43
                free(ret[i]);
44
            free(ret);
45
            return NULL;
46
        }
47 182 up20180642
        strcpy(ret[i], line_buf);
48
        ret[i][sz-1] = '\0';
49
    }
50
    fclose(f); f = NULL;
51
    return ret;
52
}