chiark / gitweb /
update IMPORT= file/stdout property parsing
[elogind.git] / udev / udev-util-file.c
1 /*
2  * Copyright (C) 2004-2008 Kay Sievers <kay.sievers@vrfy.org>
3  *
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 2 of the License, or
7  * (at your option) any later version.
8  *
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.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <stddef.h>
21 #include <unistd.h>
22 #include <string.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <ctype.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28 #include <sys/mman.h>
29
30 #include "udev.h"
31
32 int file_map(const char *filename, char **buf, size_t *bufsize)
33 {
34         struct stat stats;
35         int fd;
36
37         fd = open(filename, O_RDONLY);
38         if (fd < 0) {
39                 return -1;
40         }
41
42         if (fstat(fd, &stats) < 0) {
43                 close(fd);
44                 return -1;
45         }
46
47         *buf = mmap(NULL, stats.st_size, PROT_READ, MAP_SHARED, fd, 0);
48         if (*buf == MAP_FAILED) {
49                 close(fd);
50                 return -1;
51         }
52         *bufsize = stats.st_size;
53
54         close(fd);
55
56         return 0;
57 }
58
59 void file_unmap(void *buf, size_t bufsize)
60 {
61         munmap(buf, bufsize);
62 }
63
64 /* return number of chars until the next newline, skip escaped newline */
65 size_t buf_get_line(const char *buf, size_t buflen, size_t cur)
66 {
67         int escape = 0;
68         size_t count;
69
70         for (count = cur; count < buflen; count++) {
71                 if (!escape && buf[count] == '\n')
72                         break;
73
74                 if (buf[count] == '\\')
75                         escape = 1;
76                 else
77                         escape = 0;
78         }
79
80         return count - cur;
81 }