2 * Copyright (C) 2012-2013 Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
35 * line should be an allocated buffer given to append_line
36 * this means, free(line) will be called when decfile is released
38 static int append_line(struct rnet_decfile *decfile, char *line)
42 decfile->lines_len += 1;
43 len = sizeof(*decfile->lines) * decfile->lines_len;
44 old_lines = decfile->lines;
45 decfile->lines = realloc(decfile->lines, len);
46 if (!decfile->lines) {
47 decfile->lines = old_lines;
50 decfile->lines[decfile->lines_len - 1] = line;
53 decfile->lines_len -= 1;
57 static void decfile_release_lines(struct rnet_decfile *decfile)
60 for (i = 0; i < decfile->lines_len; i++)
61 free(decfile->lines[i]);
63 decfile->lines = NULL;
66 static int decfile_parse(struct rnet_decfile *decfile)
71 while ((r = getline(&buffer, &len, decfile->file)) > 0) {
72 r = append_line(decfile, buffer);
82 decfile_release_lines(decfile);
86 struct rnet_decfile * rnet_decfile_open(char *filename)
88 struct rnet_decfile *decfile;
89 decfile = malloc(sizeof(*decfile));
92 decfile->filename = strdup(filename);
93 if (!decfile->filename)
95 decfile->file = fopen(filename, "r");
98 decfile->lines_len = 0;
99 decfile->lines = NULL;
100 if (decfile_parse(decfile))
104 fclose(decfile->file);
106 free(decfile->filename);
112 void rnet_decfile_close(struct rnet_decfile *decfile)
114 decfile_release_lines(decfile);
115 fclose(decfile->file);
116 free(decfile->filename);