From f9eed9cc42dee01ac16a4dd968607f0ac84667c6 Mon Sep 17 00:00:00 2001 From: Jeremy Kerr Date: Fri, 24 Aug 2012 19:58:21 +0800 Subject: [PATCH] fileio: Add fileio_read_file_noerror() We may want to read files which can be absent. In this case, we don't want to print an error. This change adds fileio_read_file_noerror(), which suppresses error output. Signed-off-by: Jeremy Kerr --- src/fileio.c | 41 +++++++++++++++++++++++++---------------- src/fileio.h | 2 ++ 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/src/fileio.c b/src/fileio.c index f55d3a4..faab3b7 100644 --- a/src/fileio.c +++ b/src/fileio.c @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include @@ -45,6 +45,8 @@ #include "fileio.h" +#define FLAG_NOERROR (1<<0) + EVP_PKEY *fileio_read_pkey(const char *filename) { EVP_PKEY *key = NULL; @@ -86,8 +88,8 @@ out: return cert; } -int fileio_read_file(void *ctx, const char *filename, - uint8_t **out_buf, size_t *out_len) +static int __fileio_read_file(void *ctx, const char *filename, + uint8_t **out_buf, size_t *out_len, int flags) { struct stat statbuf; uint8_t *buf; @@ -97,29 +99,21 @@ int fileio_read_file(void *ctx, const char *filename, rc = -1; fd = open(filename, O_RDONLY); - if (fd < 0) { - perror("open"); + if (fd < 0) goto out; - } rc = fstat(fd, &statbuf); - if (rc) { - perror("fstat"); + if (rc) goto out; - } len = statbuf.st_size; buf = talloc_array(ctx, uint8_t, len); - if (!buf) { - perror("talloc"); + if (!buf) goto out; - } - if (!read_all(fd, buf, len)) { - perror("read_all"); + if (!read_all(fd, buf, len)) goto out; - } rc = 0; @@ -127,7 +121,9 @@ out: if (fd >= 0) close(fd); if (rc) { - fprintf(stderr, "Error reading file %s\n", filename); + if (!(flags & FLAG_NOERROR)) + fprintf(stderr, "Error reading file %s: %s\n", + filename, strerror(errno)); } else { *out_buf = buf; *out_len = len; @@ -136,6 +132,19 @@ out: } +int fileio_read_file(void *ctx, const char *filename, + uint8_t **out_buf, size_t *out_len) +{ + return __fileio_read_file(ctx, filename, out_buf, out_len, 0); +} + +int fileio_read_file_noerror(void *ctx, const char *filename, + uint8_t **out_buf, size_t *out_len) +{ + return __fileio_read_file(ctx, filename, out_buf, out_len, + FLAG_NOERROR); +} + int fileio_write_file(const char *filename, uint8_t *buf, size_t len) { int fd; diff --git a/src/fileio.h b/src/fileio.h index 1673a06..52c3c12 100644 --- a/src/fileio.h +++ b/src/fileio.h @@ -42,6 +42,8 @@ X509 *fileio_read_cert(const char *filename); int fileio_read_file(void *ctx, const char *filename, uint8_t **out_buf, size_t *out_len); +int fileio_read_file_noerror(void *ctx, const char *filename, + uint8_t **out_buf, size_t *out_len); int fileio_write_file(const char *filename, uint8_t *buf, size_t len); #endif /* FILEIO_H */