dir_reader_unix.h 2.19 KB
Newer Older
1 2 3 4 5 6 7
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11 12 13 14 15 16
// 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.
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 47 48 49

// 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
50
    if(NULL != dir_){
51 52 53 54 55 56 57 58 59 60 61
        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
62
    if(0 != err || NULL == current_){
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 89 90 91
        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_