diff options
author | Maximilian Brune <maximilian.brune@9elements.com> | 2024-05-09 02:53:51 +0200 |
---|---|---|
committer | Lean Sheng Tan <sheng.tan@9elements.com> | 2024-05-21 13:44:39 +0000 |
commit | 25c737d403818a92dfeb06e29ffaf04102d0f260 (patch) | |
tree | d27d4e1a366a8f8aab0e338d0f3ee577b640d339 /tests/helpers | |
parent | 62a6188da5080d17afe33a2de9218c7313c2e64b (diff) |
tests/lib: Factor out file related functions
Signed-off-by: Maximilian Brune <maximilian.brune@9elements.com>
Change-Id: I5c22913b35848c5ea32d6805ea081abefd3380bf
Reviewed-on: https://review.coreboot.org/c/coreboot/+/82237
Reviewed-by: Julius Werner <jwerner@chromium.org>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-by: Jakub Czapiga <czapiga@google.com>
Diffstat (limited to 'tests/helpers')
-rw-r--r-- | tests/helpers/file.c | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/tests/helpers/file.c b/tests/helpers/file.c new file mode 100644 index 0000000000..53f4f12dc6 --- /dev/null +++ b/tests/helpers/file.c @@ -0,0 +1,51 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include <fcntl.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + +/* + * Get the file size of a given file + * + * @params fname name of the file relative to the __TEST_DATA_DIR__ directory + * + * @return On success file size in bytes is returned. On failure -1 is returned. + */ +int test_get_file_size(const char *fname) +{ + char path[strlen(__TEST_DATA_DIR__) + strlen(fname) + 2]; + sprintf(path, "%s/%s", __TEST_DATA_DIR__, fname); + + struct stat st; + if (stat(path, &st) == -1) + return -1; + return st.st_size; +} + +/* + * Read a file and write its contents into a buffer + * + * @params fname name of the file relative to the __TEST_DATA_DIR__ directory + * @params buf buffer to write file contents into + * @params size size of buf + * + * @return On success number of bytes read is returned. On failure -1 is returned. + */ +int test_read_file(const char *fname, uint8_t *buf, size_t size) +{ + char path[strlen(__TEST_DATA_DIR__) + strlen(fname) + 2]; + sprintf(path, "%s/%s", __TEST_DATA_DIR__, fname); + + int f = open(path, O_RDONLY); + if (f == -1) + return -1; + + int read_size = read(f, buf, size); + + close(f); + return read_size; +} |