2 * Copyright (C) 2013 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
22 #include "private/bionic_macros.h"
23 #include "private/ScopedReaddir.h"
25 // A smart pointer to the scandir dirent**.
28 ScandirResult() : names_(NULL), size_(0), capacity_(0) {
33 free(names_[--size_]);
43 dirent** result = names_;
45 size_ = capacity_ = 0;
49 bool Add(dirent* entry) {
50 if (size_ >= capacity_) {
51 size_t new_capacity = capacity_ + 32;
53 reinterpret_cast<dirent**>(realloc(names_, new_capacity * sizeof(dirent*)));
54 if (new_names == NULL) {
58 capacity_ = new_capacity;
61 dirent* copy = CopyDirent(entry);
65 names_[size_++] = copy;
69 void Sort(int (*comparator)(const dirent**, const dirent**)) {
70 // If we have entries and a comparator, sort them.
71 if (size_ > 0 && comparator != NULL) {
72 qsort(names_, size_, sizeof(dirent*),
73 reinterpret_cast<int (*)(const void*, const void*)>(comparator));
82 static dirent* CopyDirent(dirent* original) {
83 // Allocate the minimum number of bytes necessary, rounded up to a 4-byte boundary.
84 size_t size = ((original->d_reclen + 3) & ~3);
85 dirent* copy = reinterpret_cast<dirent*>(malloc(size));
86 memcpy(copy, original, original->d_reclen);
90 DISALLOW_COPY_AND_ASSIGN(ScandirResult);
93 int scandir(const char* dirname, dirent*** name_list,
94 int (*filter)(const dirent*),
95 int (*comparator)(const dirent**, const dirent**)) {
96 ScopedReaddir reader(dirname);
103 while ((entry = reader.ReadEntry()) != NULL) {
104 // If we have a filter, skip names that don't match.
105 if (filter != NULL && !(*filter)(entry)) {
111 names.Sort(comparator);
113 size_t size = names.size();
114 *name_list = names.release();
117 __strong_alias(scandir64, scandir);