acezen
3/10/2018 - 1:51 AM

C++ snippets

some C++ code snippets

# check directory empty
#include <dirent.h>
#include <boost::filesystem.hpp>
#include <string>

bool IsEmpty(const std::string& path) {
  int n = 0;
  struct dirent *d;
  DIR *dir = opendir(path);
  if (dir == NULL) //Not a directory or doesn't exist
    return false;
  
  while ((d = readdir(dir)) != NULL) {
    if (++n > 2)
      break;
  }
  closedir(dir);
  if (n <= 2) //Directory Empty
    return true;
  else
    return false;
}


bool IsEmpty(const std::string& path) {
  if (!boost::filesystem::is_directory(path)) { return false; }
  
  boost::filesystem::directory_iterator end_it;
  boost::filesystem::directory_iterator it(path);
  if(it == end_it)
    return false;
  else
    return true;
}
# check file exist
#include <sys/stat.h>
#include <unistd.h>
#include <boost/filesystem.hpp>
#include <string.h>

bool IsExist(const std::string& path) {
  struct stat statbuf;
  if (stat(path.c_str(), statbuf) != -1) {
    if (S_ISDIR(statbuf.st_mode)) {
      return true; // is directory
    } else {
      return false; // is file
    }
  } else {
    return false;
  }
}


bool IsExist(const std::string& path) {
  if (access(path.c_str(), 0) != -1) { return true; }
  return false;
}


bool IsExist(const std::string& path) {
  ifstream f(path.c_str());
  return f.good();
}


bool IsExist(const string& path) {
  if (boost::filesystem::exists(path)) { return true; }
  return false;
}