[PATCH v2 012/113] libfile: factor out read_file_into_buf helper

Ahmad Fatoum a.fatoum at pengutronix.de
Mon Mar 4 10:58:57 PST 2024


We do open -> read_full -> close at a number of places. Add a function
that does this all at once and start using it to implement read_file.

More users can follow later.

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 include/libfile.h |  4 ++++
 lib/libfile.c     | 44 ++++++++++++++++++++++++++++++--------------
 2 files changed, 34 insertions(+), 14 deletions(-)

diff --git a/include/libfile.h b/include/libfile.h
index 423e7ffec5b7..1240276e1d74 100644
--- a/include/libfile.h
+++ b/include/libfile.h
@@ -2,12 +2,16 @@
 #ifndef __LIBFILE_H
 #define __LIBFILE_H
 
+#include <linux/types.h>
+
 int pread_full(int fd, void *buf, size_t size, loff_t offset);
 int pwrite_full(int fd, const void *buf, size_t size, loff_t offset);
 int write_full(int fd, const void *buf, size_t size);
 int read_full(int fd, void *buf, size_t size);
 int copy_fd(int in, int out);
 
+ssize_t read_file_into_buf(const char *filename, void *buf, size_t size);
+
 char *read_file_line(const char *fmt, ...);
 
 void *read_file(const char *filename, size_t *size);
diff --git a/lib/libfile.c b/lib/libfile.c
index 185c7af721b5..67fc9cc7f3a2 100644
--- a/lib/libfile.c
+++ b/lib/libfile.c
@@ -186,6 +186,33 @@ char *read_file_line(const char *fmt, ...)
 }
 EXPORT_SYMBOL_GPL(read_file_line);
 
+/**
+ * read_file_into_buf - read a file to an external buffer
+ * @filename:  The filename to read
+ * @buf:       The buffer to read into
+ * @size:      The buffer size
+ *
+ * This function reads a file to an external buffer. At maximum @size
+ * bytes are read.
+ *
+ * Return: number of bytes read, or negative error code.
+ */
+ssize_t read_file_into_buf(const char *filename, void *buf, size_t size)
+{
+	int fd;
+	ssize_t ret;
+
+	fd = open(filename, O_RDONLY);
+	if (fd < 0)
+		return fd;
+
+	ret = read_full(fd, buf, size);
+
+	close(fd);
+
+	return ret;
+}
+
 /**
  * read_file_2 - read a file to an allocated buffer
  * @filename:  The filename to read
@@ -208,11 +235,10 @@ EXPORT_SYMBOL_GPL(read_file_line);
 int read_file_2(const char *filename, size_t *size, void **outbuf,
 		loff_t max_size)
 {
-	int fd;
 	struct stat s;
 	void *buf = NULL;
 	const char *tmpfile = "/.read_file_tmp";
-	int ret;
+	ssize_t ret;
 	loff_t read_size;
 
 again:
@@ -240,17 +266,9 @@ int read_file_2(const char *filename, size_t *size, void **outbuf,
 		goto err_out;
 	}
 
-	fd = open(filename, O_RDONLY);
-	if (fd < 0) {
-		ret = fd;
-		goto err_out;
-	}
-
-	ret = read_full(fd, buf, read_size);
+	ret = read_file_into_buf(filename, buf, read_size);
 	if (ret < 0)
-		goto err_out1;
-
-	close(fd);
+		goto err_out;
 
 	if (size)
 		*size = ret;
@@ -265,8 +283,6 @@ int read_file_2(const char *filename, size_t *size, void **outbuf,
 
 	return 0;
 
-err_out1:
-	close(fd);
 err_out:
 	free(buf);
 
-- 
2.39.2




More information about the barebox mailing list