support for binding :commands to keys
[cmus.git] / cmus / file_load.c
blobb8b9bd973e61d274975a730791357923a989bf30
1 /*
2 * Copyright 2004 Timo Hirvonen
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
17 * 02111-1307, USA.
20 #include <file_load.h>
21 #include <xmalloc.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <string.h>
26 #include <errno.h>
28 int file_load(const char *filename,
29 void (*handle_line)(void *data, const char *line), void *data)
31 char *buffer;
32 size_t buffer_size = 4096;
33 int pos = 0;
34 int fd;
36 fd = open(filename, O_RDONLY);
37 if (fd == -1)
38 return -1;
39 buffer = xnew(char, buffer_size);
40 while (1) {
41 int i, start, len, rc;
43 rc = read(fd, buffer + pos, buffer_size - pos);
44 if (rc == -1) {
45 int save = errno;
47 free(buffer);
48 close(fd);
49 errno = save;
50 return -1;
52 if (rc == 0) {
53 if (pos > 0) {
54 /* handle line without '\n' */
55 buffer[pos] = 0;
56 handle_line(data, buffer);
58 free(buffer);
59 close(fd);
60 return 0;
62 start = 0;
63 len = pos + rc;
64 i = 0;
65 while (i < len) {
66 if (buffer[start + i] == '\n') {
67 buffer[start + i] = 0;
68 handle_line(data, buffer + start);
69 start += i + 1;
70 len -= i + 1;
71 i = 0;
72 } else {
73 i++;
76 if (start == 0) {
77 /* line doesn't fit into the buffer */
78 buffer_size *= 2;
79 buffer = xrenew(char, buffer, buffer_size);
80 } else if (len) {
81 /* len - start bytes left */
82 memmove(buffer, buffer + start, len);
84 pos = len;