1 /*
2  * Copyright (c) 2024 Tenstorrent AI ULC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #undef _POSIX_C_SOURCE
8 #define _POSIX_C_SOURCE 200809L
9 
10 #include "fs_priv.h"
11 
12 #include <errno.h>
13 #include <limits.h>
14 #include <string.h>
15 
16 #include <zephyr/fs/fs.h>
17 #include <zephyr/posix/posix_features.h>
18 #include <zephyr/posix/dirent.h>
19 #include <zephyr/sys/util.h>
20 
readdir_r(DIR * dirp,struct dirent * entry,struct dirent ** result)21 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
22 {
23 	int rc;
24 	struct fs_dirent de;
25 	struct posix_fs_desc *const ptr = dirp;
26 
27 	if (result == NULL) {
28 		return EINVAL;
29 	}
30 
31 	if (entry == NULL) {
32 		*result = NULL;
33 		return EINVAL;
34 	}
35 
36 	if (dirp == NULL) {
37 		*result = NULL;
38 		return EBADF;
39 	}
40 
41 	rc = fs_readdir(&ptr->dir, &de);
42 	if (rc < 0) {
43 		*result = NULL;
44 		return -rc;
45 	}
46 
47 	strncpy(entry->d_name, de.name, MIN(sizeof(entry->d_name), sizeof(de.name)));
48 	entry->d_name[sizeof(entry->d_name) - 1] = '\0';
49 
50 	if (entry->d_name[0] == '\0') {
51 		*result = NULL;
52 		return 0;
53 	}
54 
55 	*result = entry;
56 	return 0;
57 }
58