[PATCH 2/3] lib: open_and_lseek(): return error code on error

Sascha Hauer s.hauer at pengutronix.de
Wed Aug 16 02:39:01 PDT 2023


Some callers of open_and_lseek() expect an error code instead of -1
as return value, so consistently return an error code.

Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 lib/libfile.c | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/lib/libfile.c b/lib/libfile.c
index ebd1de3d8e..c7ea4e497f 100644
--- a/lib/libfile.c
+++ b/lib/libfile.c
@@ -589,7 +589,7 @@ int compare_file(const char *f1, const char *f2)
  * @pos:	The position to lseek to
  *
  * Return: If successful this function returns a positive
- *         filedescriptor number, otherwise -1 is returned
+ *         filedescriptor number, otherwise a negative error code is returned
  */
 int open_and_lseek(const char *filename, int mode, loff_t pos)
 {
@@ -607,26 +607,30 @@ int open_and_lseek(const char *filename, int mode, loff_t pos)
 	if (mode & (O_WRONLY | O_RDWR)) {
 		struct stat s;
 
-		if (fstat(fd, &s)) {
+		ret = fstat(fd, &s);
+		if (ret < 0) {
 			perror("fstat");
 			goto out;
 		}
 
-		if (s.st_size < pos && ftruncate(fd, pos)) {
-			perror("ftruncate");
-			goto out;
-		}
+		if (s.st_size < pos) {
+			ret = ftruncate(fd, pos));
+			if (ret) {
+				perror("ftruncate");
+				goto out;
+			}
 	}
 
 	if (lseek(fd, pos, SEEK_SET) != pos) {
 		perror("lseek");
+		ret = -errno;
 		goto out;
 	}
 
 	return fd;
 out:
 	close(fd);
-	return -1;
+	return ret;
 }
 
 /**
-- 
2.39.2




More information about the barebox mailing list