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/ScopedReaddir.h"
24 // A smart pointer to the scandir dirent**.
27 ScandirResult() : names_(NULL), size_(0), capacity_(0) {
32 free(names_[--size_]);
42 dirent** result = names_;
44 size_ = capacity_ = 0;
48 bool Add(dirent* entry) {
49 if (size_ >= capacity_) {
50 size_t new_capacity = capacity_ + 32;
51 dirent** new_names = (dirent**) realloc(names_, new_capacity * sizeof(dirent*));
52 if (new_names == NULL) {
56 capacity_ = new_capacity;
59 dirent* copy = CopyDirent(entry);
63 names_[size_++] = copy;
67 void Sort(int (*comparator)(const dirent**, const dirent**)) {
68 // If we have entries and a comparator, sort them.
69 if (size_ > 0 && comparator != NULL) {
70 qsort(names_, size_, sizeof(dirent*), (int (*)(const void*, const void*)) comparator);
79 static dirent* CopyDirent(dirent* original) {
80 // Allocate the minimum number of bytes necessary, rounded up to a 4-byte boundary.
81 size_t size = ((original->d_reclen + 3) & ~3);
82 dirent* copy = (dirent*) malloc(size);
83 memcpy(copy, original, original->d_reclen);
87 // Disallow copy and assignment.
88 ScandirResult(const ScandirResult&);
89 void operator=(const ScandirResult&);
92 int scandir(const char* dirname, dirent*** name_list,
93 int (*filter)(const dirent*),
94 int (*comparator)(const dirent**, const dirent**)) {
95 ScopedReaddir reader(dirname);
102 while ((entry = reader.ReadEntry()) != NULL) {
103 // If we have a filter, skip names that don't match.
104 if (filter != NULL && !(*filter)(entry)) {
110 names.Sort(comparator);
112 size_t size = names.size();
113 *name_list = names.release();