| 175 | } |
| 176 | |
| 177 | _TINYDIR_FUNC |
| 178 | int tinydir_open_sorted(tinydir_dir *dir, const char *path) { |
| 179 | /* Count the number of files first, to pre-allocate the files array */ |
| 180 | size_t n_files = 0; |
| 181 | if (tinydir_open(dir, path) == -1) { |
| 182 | return -1; |
| 183 | } |
| 184 | while (dir->has_next) { |
| 185 | n_files++; |
| 186 | if (tinydir_next(dir) == -1) { |
| 187 | goto bail; |
| 188 | } |
| 189 | } |
| 190 | tinydir_close(dir); |
| 191 | |
| 192 | if (tinydir_open(dir, path) == -1) { |
| 193 | return -1; |
| 194 | } |
| 195 | |
| 196 | dir->n_files = 0; |
| 197 | dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files); |
| 198 | if (dir->_files == NULL) { |
| 199 | errno = ENOMEM; |
| 200 | goto bail; |
| 201 | } |
| 202 | while (dir->has_next) { |
| 203 | tinydir_file *p_file; |
| 204 | dir->n_files++; |
| 205 | |
| 206 | p_file = &dir->_files[dir->n_files - 1]; |
| 207 | if (tinydir_readfile(dir, p_file) == -1) { |
| 208 | goto bail; |
| 209 | } |
| 210 | |
| 211 | if (tinydir_next(dir) == -1) { |
| 212 | goto bail; |
| 213 | } |
| 214 | |
| 215 | /* Just in case the number of files has changed between the first and |
| 216 | second reads, terminate without writing into unallocated memory */ |
| 217 | if (dir->n_files == n_files) { |
| 218 | break; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp); |
| 223 | |
| 224 | return 0; |
| 225 | |
| 226 | bail: |
| 227 | tinydir_close(dir); |
| 228 | return -1; |
| 229 | } |
| 230 | |
| 231 | _TINYDIR_FUNC |
| 232 | void tinydir_close(tinydir_dir *dir) { |
no test coverage detected