dir_reader_unix.h 1.98 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
// Copyright (c) 2018 Baidu, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Authors: yinqiwen (yinqiwen@gmail.com)

#ifndef BUTIL_FILES_DIR_READER_UNIX_H_
#define BUTIL_FILES_DIR_READER_UNIX_H_

#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <dirent.h>

#include "butil/logging.h"
#include "butil/posix/eintr_wrapper.h"

// See the comments in dir_reader_posix.h about this.

namespace butil {

class DirReaderUnix {
 public:
  explicit DirReaderUnix(const char* directory_path)
      : fd_(open(directory_path, O_RDONLY | O_DIRECTORY)),
        dir_(NULL),current_(NULL) {
      dir_ = fdopendir(fd_);
  }

  ~DirReaderUnix() {
    if (fd_ >= 0) {
      if (IGNORE_EINTR(close(fd_)))
        RAW_LOG(ERROR, "Failed to close directory handle");
    }
yinqiwen's avatar
yinqiwen committed
47
    if(NULL != dir_){
48 49 50 51 52 53 54 55 56 57 58
        closedir(dir_);
    }
  }

  bool IsValid() const {
    return fd_ >= 0;
  }

  // Move to the next entry returning false if the iteration is complete.
  bool Next() {
    int err = readdir_r(dir_,&entry_, &current_);
yinqiwen's avatar
yinqiwen committed
59
    if(0 != err || NULL == current_){
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        return false;
    }
    return true;
  }

  const char* name() const {
    if (NULL == current_)
      return NULL;
    return current_->d_name;
  }

  int fd() const {
    return fd_;
  }

  static bool IsFallback() {
    return false;
  }

 private:
  const int fd_;
  DIR* dir_;
  struct dirent entry_;
  struct dirent* current_;
};

}  // namespace butil

#endif // BUTIL_FILES_DIR_READER_LINUX_H_