Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

filesystem.cpp 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // \file filesystem.cpp
  2. //
  3. // Copyright (C) 2014 MicroNeil Research Corporation.
  4. //
  5. // This program is part of the MicroNeil Research Open Library Project. For
  6. // more information go to http://www.microneil.com/OpenLibrary/index.html
  7. //
  8. // This program is free software; you can redistribute it and/or modify it
  9. // under the terms of the GNU General Public License as published by the
  10. // Free Software Foundation; either version 2 of the License, or (at your
  11. // option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful, but WITHOUT
  14. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. // more details.
  17. //
  18. // You should have received a copy of the GNU General Public License along with
  19. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  20. // Place, Suite 330, Boston, MA 02111-1307 USA
  21. //==============================================================================
  22. #ifdef _WIN32
  23. #include <windows.h>
  24. #else
  25. #include <dirent.h>
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #include <cstdlib>
  29. #include <cstring>
  30. #include <cerrno>
  31. #endif
  32. #include <sys/stat.h>
  33. #include <stdexcept>
  34. #include "filesystem.hpp"
  35. namespace CodeDweller {
  36. #ifdef _WIN32
  37. char const FilePath::DirectorySeparator = '\\';
  38. #else
  39. char const FilePath::DirectorySeparator = '/';
  40. #endif
  41. std::string FilePath::join(std::initializer_list<std::string> components) {
  42. std::string path;
  43. for (auto &component : components) {
  44. if (!path.empty() &&
  45. path.back() != FilePath::DirectorySeparator) {
  46. path += FilePath::DirectorySeparator;
  47. }
  48. path += component;
  49. }
  50. if (!path.empty() &&
  51. path.back() == FilePath::DirectorySeparator) {
  52. path.pop_back();
  53. }
  54. return path;
  55. }
  56. FileReference::FileReference(std::string fileName) :
  57. name(fileName),
  58. modTimestamp(0),
  59. size_bytes(0),
  60. fileExists(false),
  61. fileIsDirectory(false) {
  62. refresh();
  63. }
  64. void FileReference::refresh() {
  65. reset();
  66. // Load info.
  67. struct stat statBuffer;
  68. int status = stat(name.c_str(), &statBuffer);
  69. if (-1 == status) {
  70. // File no longer exists.
  71. if (ENOENT == errno) {
  72. return;
  73. }
  74. // Something went wrong.
  75. throw std::runtime_error("Error updating status of file \"" +
  76. name + "\": " + getErrorText());
  77. }
  78. modTimestamp = statBuffer.st_mtime;
  79. size_bytes = statBuffer.st_size;
  80. fileExists = true;
  81. fileIsDirectory = S_ISDIR(statBuffer.st_mode);
  82. }
  83. void FileReference:: reset() {
  84. modTimestamp = 0;
  85. size_bytes = 0;
  86. fileExists = false;
  87. fileIsDirectory = false;
  88. path.clear();
  89. }
  90. time_t FileReference::ModTimestamp() const {
  91. return modTimestamp;
  92. }
  93. size_t FileReference::Size() const {
  94. return size_bytes;
  95. }
  96. std::string FileReference::FullPath() {
  97. if (!path.empty()) {
  98. return path;
  99. }
  100. if (!fileExists) {
  101. return "";
  102. }
  103. #ifdef _WIN32
  104. // Get the size of the full path name.
  105. DWORD nTchars = GetFullPathName(name.c_str(), 0, NULL, NULL);
  106. if (0 == nTchars) {
  107. throw std::runtime_error("Error getting full path length for \"" + name
  108. + "\": " + getErrorText());
  109. }
  110. size_t bufSize = nTchars * sizeof(TCHAR);
  111. TCHAR fullPath[bufSize];
  112. nTchars = GetFullPathName(name.c_str(), bufSize, fullPath, NULL);
  113. if (0 == nTchars) {
  114. throw std::runtime_error("Error getting full path for \"" + name
  115. + "\": " + getErrorText());
  116. }
  117. path.assign(fullPath);
  118. #else
  119. char *realPath = realpath(name.c_str(), NULL);
  120. if (NULL == realPath) {
  121. // Nothing to do if the file doesn't exist.
  122. if (ENOENT == errno) {
  123. reset();
  124. return "";
  125. }
  126. // Something went wrong.
  127. throw std::runtime_error("Error checking file \"" + name + "\": " +
  128. getErrorText());
  129. }
  130. path.assign(realPath);
  131. free(realPath);
  132. #endif
  133. return path;
  134. }
  135. bool FileReference::exists() const {
  136. return fileExists;
  137. }
  138. bool FileReference::isDirectory() const {
  139. return fileIsDirectory;
  140. }
  141. std::string FileReference::getErrorText() {
  142. #ifdef _WIN32
  143. LPVOID winMsgBuf;
  144. DWORD lastError = GetLastError();
  145. FormatMessage(
  146. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  147. FORMAT_MESSAGE_FROM_SYSTEM |
  148. FORMAT_MESSAGE_IGNORE_INSERTS,
  149. NULL,
  150. lastError,
  151. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  152. (char *) &winMsgBuf,
  153. 0, NULL );
  154. std::string errMsg((char *) winMsgBuf);
  155. LocalFree(winMsgBuf);
  156. return errMsg;
  157. #else
  158. return strerror(errno);
  159. #endif
  160. }
  161. DirectoryReference::DirectoryReference(std::string dirName,
  162. bool (*dirFilter)(std::string)) :
  163. name(dirName),
  164. filter(dirFilter) {
  165. refresh();
  166. }
  167. void DirectoryReference::refresh() {
  168. // Clear any entries in this object.
  169. this->clear();
  170. #ifdef _WIN32
  171. HANDLE hDirList;
  172. WIN32_FIND_DATA dirListData;
  173. std::string searchString = FilePath::join({name, "*"});
  174. hDirList = FindFirstFile(searchString.c_str(), &dirListData);
  175. if (INVALID_HANDLE_VALUE == hDirList) {
  176. throw std::runtime_error("Error getting file list for \"" + name +
  177. "\": " + FileReference::getErrorText());
  178. }
  179. std::string tempName;
  180. while (INVALID_HANDLE_VALUE != hDirList) {
  181. tempName = FilePath::join({name, dirListData.cFileName});
  182. if ( (0 == filter) || (*filter)(dirListData.cFileName)) {
  183. emplace_back(tempName);
  184. }
  185. if (!FindNextFile(hDirList, &dirListData)) {
  186. FindClose(hDirList);
  187. hDirList = INVALID_HANDLE_VALUE;
  188. }
  189. }
  190. #else
  191. // Get new list.
  192. struct dirent **entries;
  193. int nEntries = scandir(name.c_str(), &entries, 0, 0);
  194. if (nEntries < 0) {
  195. throw std::runtime_error("Error getting file list for \"" + name +
  196. "\": " + FileReference::getErrorText());
  197. }
  198. // Create the FileReference objects.
  199. while (nEntries--) {
  200. std::string tempName;
  201. tempName = FilePath::join({name, entries[nEntries]->d_name});
  202. if ( (0 == filter) || (*filter)(entries[nEntries]->d_name)) {
  203. emplace_back(tempName);
  204. }
  205. free(entries[nEntries]);
  206. }
  207. free(entries);
  208. #endif
  209. }
  210. }