ctdb-build: Add generation of Samba-style version.h
[Samba.git] / ctdb / lib / util / util_file.c
blob5db007206185cc49541f75bec6162a1c10afd019
1 /*
2 functions taken from samba4 for quick prototyping of ctdb. These are
3 not intended to remain part of ctdb
4 */
6 #include <assert.h>
8 #include "includes.h"
9 #include "system/filesys.h"
12 static char *fd_load(int fd, size_t *size, TALLOC_CTX *mem_ctx)
14 struct stat sbuf;
15 char *p;
17 if (fstat(fd, &sbuf) != 0) return NULL;
19 p = (char *)talloc_size(mem_ctx, sbuf.st_size+1);
20 if (!p) return NULL;
22 if (read(fd, p, sbuf.st_size) != sbuf.st_size) {
23 talloc_free(p);
24 return NULL;
26 p[sbuf.st_size] = 0;
28 if (size) *size = sbuf.st_size;
30 return p;
34 static char *file_load(const char *fname, size_t *size, TALLOC_CTX *mem_ctx)
36 int fd;
37 char *p;
39 if (!fname || !*fname) return NULL;
41 fd = open(fname,O_RDONLY);
42 if (fd == -1) return NULL;
44 p = fd_load(fd, size, mem_ctx);
46 close(fd);
48 return p;
52 /**
53 parse a buffer into lines
54 'p' will be freed on error, and otherwise will be made a child of the returned array
55 **/
56 static char **file_lines_parse(char *p, size_t size, int *numlines, TALLOC_CTX *mem_ctx)
58 int i;
59 char *s, **ret;
61 if (!p) return NULL;
63 for (s = p, i=0; s < p+size; s++) {
64 if (s[0] == '\n') i++;
67 ret = talloc_array(mem_ctx, char *, i+2);
68 if (!ret) {
69 talloc_free(p);
70 return NULL;
73 talloc_steal(ret, p);
75 memset(ret, 0, sizeof(ret[0])*(i+2));
76 if (numlines) *numlines = i;
78 ret[0] = p;
79 for (s = p, i=0; s < p+size; s++) {
80 if (s[0] == '\n') {
81 s[0] = 0;
82 i++;
83 ret[i] = s+1;
85 if (s[0] == '\r') s[0] = 0;
88 return ret;
92 /**
93 load a file into memory and return an array of pointers to lines in the file
94 must be freed with talloc_free().
95 **/
96 _PUBLIC_ char **file_lines_load(const char *fname, int *numlines, size_t maxsize, TALLOC_CTX *mem_ctx)
98 char *p;
99 size_t size;
101 assert(maxsize == 0);
103 p = file_load(fname, &size, mem_ctx);
104 if (!p) return NULL;
106 return file_lines_parse(p, size, numlines, mem_ctx);
109 char *hex_encode_talloc(TALLOC_CTX *mem_ctx, const unsigned char *buff_in, size_t len)
111 int i;
112 char *hex_buffer;
114 hex_buffer = talloc_array(mem_ctx, char, (len*2)+1);
116 for (i = 0; i < len; i++)
117 slprintf(&hex_buffer[i*2], 3, "%02X", buff_in[i]);
119 return hex_buffer;