pathcreator.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #include "pathcreator.h"
  2. #include <sys/types.h>
  3. #include <time.h>
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. PathCreator::PathCreator()
  7. {
  8. }
  9. PathCreator::~PathCreator()
  10. {
  11. }
  12. std::string PathCreator::GetCurPath()
  13. {
  14. return m_current_path;
  15. }
  16. bool PathCreator::Mkdir(std::string dirName)
  17. {
  18. uint32_t beginCmpPath = 0;
  19. uint32_t endCmpPath = 0;
  20. std::string fullPath = "";
  21. if('/' != dirName[0])
  22. {
  23. fullPath = getcwd(nullptr, 0);
  24. beginCmpPath = fullPath.size();
  25. fullPath = fullPath + "/" + dirName;
  26. }
  27. else
  28. {
  29. //Absolute path
  30. fullPath = dirName;
  31. beginCmpPath = 1;
  32. }
  33. if (fullPath[fullPath.size() - 1] != '/')
  34. {
  35. fullPath += "/";
  36. }
  37. endCmpPath = fullPath.size();
  38. //create dirs;
  39. for(uint32_t i = beginCmpPath; i < endCmpPath ; i++ )
  40. {
  41. if('/' == fullPath[i])
  42. {
  43. std::string curPath = fullPath.substr(0, i);
  44. if(access(curPath.c_str(), F_OK) != 0)
  45. {
  46. if(mkdir(curPath.c_str(), /*S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH*/0777) == -1)
  47. {
  48. printf("mkdir(%s) failed\n", curPath.c_str());
  49. return false;
  50. }
  51. }
  52. }
  53. }
  54. m_current_path=fullPath;
  55. return true;
  56. }
  57. bool PathCreator::CreateDatePath(std::string root, bool add_time)
  58. {
  59. time_t tt;
  60. time( &tt );
  61. tt = tt + 8*3600; // transform the time zone
  62. tm* t= gmtime( &tt );
  63. char buf[255]={0};
  64. if (add_time)
  65. {
  66. sprintf(buf, "%s/%d%02d%02d-%02d%02d%02d", root.c_str(),
  67. t->tm_year + 1900,
  68. t->tm_mon + 1,
  69. t->tm_mday,
  70. t->tm_hour,
  71. t->tm_min,
  72. t->tm_sec);
  73. }
  74. else
  75. {
  76. sprintf(buf, "%s/%d%02d%02d", root.c_str(),
  77. t->tm_year + 1900,
  78. t->tm_mon + 1,
  79. t->tm_mday);
  80. }
  81. return Mkdir(buf);
  82. }
  83. bool PathCreator::IsPathExist(const std::string& path) {
  84. if (access(path.c_str(), 0) == F_OK) {
  85. return true;
  86. }
  87. return false;
  88. }
  89. bool PathCreator::IsFile(const std::string& path) {
  90. if (!IsPathExist(path)) {
  91. printf("%s:%d %s not exist\n", __FILE__, __LINE__, path.c_str());
  92. return false;
  93. }
  94. struct stat buffer;
  95. return (stat(path.c_str(), &buffer) == 0 && S_ISREG(buffer.st_mode));
  96. }
  97. bool PathCreator::IsFolder(const std::string& path) {
  98. if (!IsPathExist(path)) {
  99. return false;
  100. }
  101. struct stat buffer;
  102. return (stat(path.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode));
  103. }