lib: Move "iov_buf.[ch]" to lib/util
[obnox/samba/samba-obnox.git] / source3 / lib / util_file.c
1 /*
2  * Unix SMB/CIFS implementation.
3  * SMB parameters and setup
4  * Copyright (C) Andrew Tridgell 1992-1998 Modified by Jeremy Allison 1995.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU General Public License as published by the Free
8  * Software Foundation; either version 3 of the License, or (at your option)
9  * any later version.
10  * 
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "includes.h"
21 #include "lib/sys_rw.h"
22
23 /**
24  Load from a pipe into memory.
25 **/
26
27 static char *file_pload(const char *syscmd, size_t *size)
28 {
29         int fd, n;
30         char *p;
31         char buf[1024];
32         size_t total;
33
34         fd = sys_popen(syscmd);
35         if (fd == -1) {
36                 return NULL;
37         }
38
39         p = NULL;
40         total = 0;
41
42         while ((n = sys_read(fd, buf, sizeof(buf))) > 0) {
43                 p = talloc_realloc(NULL, p, char, total + n + 1);
44                 if (!p) {
45                         DEBUG(0,("file_pload: failed to expand buffer!\n"));
46                         close(fd);
47                         return NULL;
48                 }
49                 memcpy(p+total, buf, n);
50                 total += n;
51         }
52
53         if (p) {
54                 p[total] = 0;
55         }
56
57         /* FIXME: Perhaps ought to check that the command completed
58          * successfully (returned 0); if not the data may be
59          * truncated. */
60         sys_pclose(fd);
61
62         if (size) {
63                 *size = total;
64         }
65
66         return p;
67 }
68
69
70
71 /**
72  Load a pipe into memory and return an array of pointers to lines in the data
73  must be freed with TALLOC_FREE.
74 **/
75
76 char **file_lines_pload(const char *syscmd, int *numlines)
77 {
78         char *p;
79         size_t size;
80
81         p = file_pload(syscmd, &size);
82         if (!p) {
83                 return NULL;
84         }
85
86         return file_lines_parse(p, size, numlines, NULL);
87 }