天天看點

Linux快速讀取檔案之檔案映射c++執行個體

typedef struct file_info_value
  {
    std::string file_name_;
    long size_;
    int fd_;
    char *buff_;
    boost::recursive_mutex cond_mtx_;
    boost::condition_variable_any cond_var_;

    boost::atomic<bool> is_mmap_;
    file_info_value(std::string file_name):file_name_(file_name),size_(0),fd_(-1),buff_(nullptr),is_mmap_(false)
    {
      fd_ = open(file_name.c_str(), O_RDONLY);
      if (fd_ == -1)
      {
        size_ = 0;
      }
      else
      {
        struct stat st;
        int r = fstat(fd_, &st);
        if (r == -1)
        {
          size_ = 0;
          close(fd_);
        }
        else
        {
          size_ = st.st_size;
        }
      }
    }
    ~file_info_value()
    {
      if (fd_ != -1)
      {
        close(fd_);
        munmap(buff_, size_);
      }
    }
    //if data is too big,create file spilt more file_index,mmap more times(hfrz ptr as start addr)
    int mmap_the_file()
    {
      if (fd_ == -1)
      {
        return -1;
      }
      buff_ = (char *)mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
      if (buff_ == (void*)-1)
      {
        std::ostringstream oslog;
        oslog << "mmap failed:"<< strerror(errno);
        LOG4CXX_INFO(log4cxx::Logger::getLogger("logger2"), oslog.str());
        close(fd_);
        return -1;
      }
      is_mmap_ = true;
      return 0;
    } 
  }file_info, *ptr_file_info;      

繼續閱讀