support: Change xgetline to return 0 on EOF

The advantage is that the buffer will always contain the number
of characters as returned from the function, which allows one to use
a sequence like

  /* No more audit module output.  */
  line_length = xgetline (&buffer, &buffer_length, fp);
  TEST_COMPARE_BLOB ("", 0, buffer, line_length);

to check for an expected EOF, while also reporting any unexpected
extra data encountered.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
This commit is contained in:
Florian Weimer 2020-04-02 17:09:36 +02:00
parent 17fd707f88
commit cea56af185
3 changed files with 19 additions and 10 deletions

View File

@ -59,7 +59,7 @@ support_process_state_wait (pid_t pid, enum support_process_state state)
for (;;) for (;;)
{ {
char cur_state = -1; char cur_state = -1;
while (xgetline (&line, &linesiz, fstatus) != -1) while (xgetline (&line, &linesiz, fstatus) > 0)
if (strncmp (line, "State:", strlen ("State:")) == 0) if (strncmp (line, "State:", strlen ("State:")) == 0)
{ {
TEST_COMPARE (sscanf (line, "%*s %c", &cur_state), 1); TEST_COMPARE (sscanf (line, "%*s %c", &cur_state), 1);

View File

@ -18,16 +18,22 @@
#include <support/xstdio.h> #include <support/xstdio.h>
#include <support/check.h> #include <support/check.h>
#include <errno.h>
ssize_t size_t
xgetline (char **lineptr, size_t *n, FILE *stream) xgetline (char **lineptr, size_t *n, FILE *stream)
{ {
int old_errno = errno; TEST_VERIFY (!ferror (stream));
errno = 0; ssize_t ret = getline (lineptr, n, stream);
size_t ret = getline (lineptr, n, stream); if (ferror (stream))
if (!feof (stream) && ferror (stream)) {
FAIL_EXIT1 ("getline failed: %m"); TEST_VERIFY (ret < 0);
errno = old_errno; FAIL_EXIT1 ("getline: %m");
}
if (feof (stream))
{
TEST_VERIFY (ret <= 0);
return 0;
}
TEST_VERIFY (ret > 0);
return ret; return ret;
} }

View File

@ -27,7 +27,10 @@ __BEGIN_DECLS
FILE *xfopen (const char *path, const char *mode); FILE *xfopen (const char *path, const char *mode);
void xfclose (FILE *); void xfclose (FILE *);
ssize_t xgetline (char **lineptr, size_t *n, FILE *stream); /* Read a line from FP, using getline. *BUFFER must be NULL, or a
heap-allocated pointer of *LENGTH bytes. Return the number of
bytes in the line if a line was read, or 0 on EOF. */
size_t xgetline (char **lineptr, size_t *n, FILE *stream);
__END_DECLS __END_DECLS