| 1 | /* Example for creating a struct dirent object for use with glob. |
| 2 | Copyright (C) 2016-2024 Free Software Foundation, Inc. |
| 3 | |
| 4 | This program is free software; you can redistribute it and/or |
| 5 | modify it under the terms of the GNU General Public License |
| 6 | as published by the Free Software Foundation; either version 2 |
| 7 | of the License, or (at your option) any later version. |
| 8 | |
| 9 | This program is distributed in the hope that it will be useful, |
| 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | GNU General Public License for more details. |
| 13 | |
| 14 | You should have received a copy of the GNU General Public License |
| 15 | along with this program; if not, see <https://www.gnu.org/licenses/>. |
| 16 | */ |
| 17 | |
| 18 | #include <dirent.h> |
| 19 | #include <errno.h> |
| 20 | #include <stddef.h> |
| 21 | #include <stdlib.h> |
| 22 | #include <string.h> |
| 23 | |
| 24 | struct dirent * |
| 25 | mkdirent (const char *name) |
| 26 | { |
| 27 | size_t dirent_size = offsetof (struct dirent, d_name) + 1; |
| 28 | size_t name_length = strlen (name); |
| 29 | size_t total_size = dirent_size + name_length; |
| 30 | if (total_size < dirent_size) |
| 31 | { |
| 32 | errno = ENOMEM; |
| 33 | return NULL; |
| 34 | } |
| 35 | struct dirent *result = malloc (size: total_size); |
| 36 | if (result == NULL) |
| 37 | return NULL; |
| 38 | result->d_type = DT_UNKNOWN; |
| 39 | result->d_ino = 1; /* Do not skip this entry. */ |
| 40 | memcpy (result->d_name, name, name_length + 1); |
| 41 | return result; |
| 42 | } |
| 43 | |