Definition and implementation of new guestfs_read_lines API call.

This commit is contained in:
Richard Jones
2009-04-08 23:47:28 +01:00
parent 45f3a89817
commit f4299f7ea5
2 changed files with 66 additions and 1 deletions

View File

@@ -18,7 +18,7 @@
#include <config.h>
#define _GNU_SOURCE /* for futimens(2) */
#define _GNU_SOURCE /* for futimens(2) and getline(3) */
#include <stdio.h>
#include <stdlib.h>
@@ -128,3 +128,55 @@ do_cat (const char *path)
return buf; /* caller will free */
}
char **
do_read_lines (const char *path)
{
char **r = NULL;
int size = 0, alloc = 0;
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t n;
NEED_ROOT (NULL);
ABS_PATH (path, NULL);
CHROOT_IN;
fp = fopen (path, "r");
CHROOT_OUT;
if (!fp) {
reply_with_perror ("fopen: %s", path);
return NULL;
}
while ((n = getline (&line, &len, fp)) != -1) {
/* Remove either LF or CRLF. */
if (n >= 2 && line[n-2] == '\r' && line[n-1] == '\n')
line[n-2] = '\0';
else if (n >= 1 && line[n-1] == '\n')
line[n-1] = '\0';
if (add_string (&r, &size, &alloc, line) == -1) {
free (line);
fclose (fp);
return NULL;
}
}
free (line);
if (add_string (&r, &size, &alloc, NULL) == -1) {
fclose (fp);
return NULL;
}
if (fclose (fp) == EOF) {
reply_with_perror ("fclose: %s", path);
free_strings (r);
return NULL;
}
return r;
}

View File

@@ -310,6 +310,19 @@ of the L<vgs(8)> command. The \"full\" version includes all fields.");
"\
List all the logical volumes detected. This is the equivalent
of the L<lvs(8)> command. The \"full\" version includes all fields.");
("read_lines", (RStringList "lines", P1 (String "path")), 15, [],
"read file as lines",
"\
Return the contents of the file named C<path>.
The file contents are returned as a list of lines. Trailing
C<LF> and C<CRLF> character sequences are I<not> returned.
Note that this function cannot correctly handle binary files
(specifically, files containing C<\\0> character which is treated
as end of line). For those you need to use the C<guestfs_read_file>
function which has a more complex interface.");
]
let all_functions = non_daemon_functions @ daemon_functions