summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorAhmad Fatoum <a.fatoum@pengutronix.de>2024-03-04 19:58:57 +0100
committerSascha Hauer <s.hauer@pengutronix.de>2024-03-05 16:28:05 +0100
commit761f51b69966202a0e8cb06723195b0eb69bbd98 (patch)
tree658c447e9307fb1494733c9745e9dc29f0972942 /lib
parentc7fbc51c572e6babd7e372960472a45daf2ef7c2 (diff)
downloadbarebox-761f51b69966202a0e8cb06723195b0eb69bbd98.tar.gz
barebox-761f51b69966202a0e8cb06723195b0eb69bbd98.tar.xz
libfile: factor out read_file_into_buf helper
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@pengutronix.de> Link: https://lore.barebox.org/20240304190038.3486881-13-a.fatoum@pengutronix.de Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
Diffstat (limited to 'lib')
-rw-r--r--lib/libfile.c44
1 files changed, 30 insertions, 14 deletions
diff --git a/lib/libfile.c b/lib/libfile.c
index 185c7af721..67fc9cc7f3 100644
--- a/lib/libfile.c
+++ b/lib/libfile.c
@@ -187,6 +187,33 @@ out:
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
* @size: After successful return contains the size of the file
@@ -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 @@ again:
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 @@ again:
return 0;
-err_out1:
- close(fd);
err_out:
free(buf);