diff options
author | Simon Glass <sjg@chromium.org> | 2021-08-18 21:40:30 -0600 |
---|---|---|
committer | Tom Rini <trini@konsulko.com> | 2021-09-16 13:19:25 -0400 |
commit | b4467fae06e7c5b48635cd28e0b168b8508ad168 (patch) | |
tree | c6bdb800ed5f2021484a0945388cc61922ff9702 | |
parent | 79b3f367304dc743518200eb6b82556890c9ae05 (diff) | |
download | u-boot-b4467fae06e7c5b48635cd28e0b168b8508ad168.zip u-boot-b4467fae06e7c5b48635cd28e0b168b8508ad168.tar.gz u-boot-b4467fae06e7c5b48635cd28e0b168b8508ad168.tar.bz2 |
sandbox: Add a way to find the size of a file
Add a function to return the size of a file. This is useful in situations
where we need to allocate memory for it before reading it.
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: Marek BehĂșn <marek.behun@nic.cz>
-rw-r--r-- | arch/sandbox/cpu/os.c | 22 | ||||
-rw-r--r-- | include/os.h | 8 |
2 files changed, 24 insertions, 6 deletions
diff --git a/arch/sandbox/cpu/os.c b/arch/sandbox/cpu/os.c index 151f42a..a426288 100644 --- a/arch/sandbox/cpu/os.c +++ b/arch/sandbox/cpu/os.c @@ -133,6 +133,19 @@ int os_write_file(const char *fname, const void *buf, int size) return 0; } +int os_filesize(int fd) +{ + off_t size; + + size = os_lseek(fd, 0, OS_SEEK_END); + if (size < 0) + return -errno; + if (os_lseek(fd, 0, OS_SEEK_SET) < 0) + return -errno; + + return size; +} + int os_read_file(const char *fname, void **bufp, int *sizep) { off_t size; @@ -144,15 +157,12 @@ int os_read_file(const char *fname, void **bufp, int *sizep) printf("Cannot open file '%s'\n", fname); goto err; } - size = os_lseek(fd, 0, OS_SEEK_END); + size = os_filesize(fd); if (size < 0) { - printf("Cannot seek to end of file '%s'\n", fname); - goto err; - } - if (os_lseek(fd, 0, OS_SEEK_SET) < 0) { - printf("Cannot seek to start of file '%s'\n", fname); + printf("Cannot get file size of '%s'\n", fname); goto err; } + *bufp = os_malloc(size); if (!*bufp) { printf("Not enough memory to read file '%s'\n", fname); diff --git a/include/os.h b/include/os.h index 7b20d60..7661078 100644 --- a/include/os.h +++ b/include/os.h @@ -52,6 +52,14 @@ off_t os_lseek(int fd, off_t offset, int whence); #define OS_SEEK_END 2 /** + * os_filesize() - Calculate the size of a file + * + * @fd: File descriptor as returned by os_open() + * Return: file size or negative error code + */ +int os_filesize(int fd); + +/** * Access to the OS open() system call * * @pathname: Pathname of file to open |