2 * Copyright 2005 Timo Hirvonen
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
23 #include <sys/types.h>
31 ssize_t
read_all(int fd
, void *buf
, size_t count
)
39 rc
= read(fd
, buffer
+ pos
, count
- pos
);
41 if (errno
== EINTR
|| errno
== EAGAIN
)
50 } while (count
- pos
> 0);
54 ssize_t
write_all(int fd
, const void *buf
, size_t count
)
56 const char *buffer
= buf
;
57 int count_save
= count
;
62 rc
= write(fd
, buffer
, count
);
64 if (errno
== EINTR
|| errno
== EAGAIN
)
74 char *mmap_file(const char *filename
, int *size
)
80 fd
= open(filename
, O_RDONLY
);
84 if (fstat(fd
, &st
) == -1)
87 /* can't mmap empty files */
90 buf
= mmap(NULL
, st
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
91 if (buf
== MAP_FAILED
)
106 void buffer_for_each_line(const char *buf
, int size
,
107 int (*cb
)(void *data
, const char *line
),
111 int line_size
= 0, pos
= 0;
117 while (end
< size
&& buf
[end
] != '\n')
121 if (end
> pos
&& buf
[end
- 1] == '\r')
124 if (len
>= line_size
) {
126 line
= xrenew(char, line
, line_size
);
128 memcpy(line
, buf
+ pos
, len
);
138 void buffer_for_each_line_reverse(const char *buf
, int size
,
139 int (*cb
)(void *data
, const char *line
),
143 int line_size
= 0, end
= size
- 1;
148 if (end
> 1 && buf
[end
] == '\n' && buf
[end
- 1] == '\r')
152 while (pos
> 0 && buf
[pos
- 1] != '\n')
156 if (len
>= line_size
) {
158 line
= xrenew(char, line
, line_size
);
160 memcpy(line
, buf
+ pos
, len
);
170 int file_for_each_line(const char *filename
,
171 int (*cb
)(void *data
, const char *line
),
177 buf
= mmap_file(filename
, &size
);
182 buffer_for_each_line(buf
, size
, cb
, data
);