xref: /aosp_15_r20/external/coreboot/tests/helpers/file.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 
3 #include <fcntl.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10 
11 /*
12  * Get the file size of a given file
13  *
14  * @params fname  name of the file relative to the __TEST_DATA_DIR__ directory
15  *
16  * @return  On success file size in bytes is returned. On failure -1 is returned.
17  */
test_get_file_size(const char * fname)18 int test_get_file_size(const char *fname)
19 {
20 	char path[strlen(__TEST_DATA_DIR__) + strlen(fname) + 2];
21 	sprintf(path, "%s/%s", __TEST_DATA_DIR__, fname);
22 
23 	struct stat st;
24 	if (stat(path, &st) == -1)
25 		return -1;
26 	return st.st_size;
27 }
28 
29 /*
30  * Read a file and write its contents into a buffer
31  *
32  * @params fname  name of the file relative to the __TEST_DATA_DIR__ directory
33  * @params buf    buffer to write file contents into
34  * @params size   size of buf
35  *
36  * @return  On success number of bytes read is returned. On failure -1 is returned.
37  */
test_read_file(const char * fname,uint8_t * buf,size_t size)38 int test_read_file(const char *fname, uint8_t *buf, size_t size)
39 {
40 	char path[strlen(__TEST_DATA_DIR__) + strlen(fname) + 2];
41 	sprintf(path, "%s/%s", __TEST_DATA_DIR__, fname);
42 
43 	int f = open(path, O_RDONLY);
44 	if (f == -1)
45 		return -1;
46 
47 	int read_size = read(f, buf, size);
48 
49 	close(f);
50 	return read_size;
51 }
52