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

filesystem.cpp 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. std::string FileReference::FileName() const {
  65. return name;
  66. }
  67. void FileReference::refresh() {
  68. reset();
  69. // Load info.
  70. struct stat statBuffer;
  71. int status = stat(name.c_str(), &statBuffer);
  72. if (-1 == status) {
  73. // File no longer exists.
  74. if (ENOENT == errno) {
  75. return;
  76. }
  77. // Something went wrong.
  78. throw std::runtime_error("Error updating status of file \"" +
  79. name + "\": " + getErrorText());
  80. }
  81. modTimestamp = statBuffer.st_mtime;
  82. size_bytes = statBuffer.st_size;
  83. fileExists = true;
  84. fileIsDirectory = S_ISDIR(statBuffer.st_mode);
  85. }
  86. void FileReference:: reset() {
  87. modTimestamp = 0;
  88. size_bytes = 0;
  89. fileExists = false;
  90. fileIsDirectory = false;
  91. path.clear();
  92. }
  93. time_t FileReference::ModTimestamp() const {
  94. return modTimestamp;
  95. }
  96. size_t FileReference::Size() const {
  97. return size_bytes;
  98. }
  99. std::string FileReference::FullPath() {
  100. if (!path.empty()) {
  101. return path;
  102. }
  103. if (!fileExists) {
  104. return "";
  105. }
  106. #ifdef _WIN32
  107. // Get the size of the full path name.
  108. DWORD nTchars = GetFullPathName(name.c_str(), 0, NULL, NULL);
  109. if (0 == nTchars) {
  110. throw std::runtime_error("Error getting full path length for \"" + name
  111. + "\": " + getErrorText());
  112. }
  113. size_t bufSize = nTchars * sizeof(TCHAR);
  114. TCHAR fullPath[bufSize];
  115. nTchars = GetFullPathName(name.c_str(), bufSize, fullPath, NULL);
  116. if (0 == nTchars) {
  117. throw std::runtime_error("Error getting full path for \"" + name
  118. + "\": " + getErrorText());
  119. }
  120. path.assign(fullPath);
  121. #else
  122. char *realPath = realpath(name.c_str(), NULL);
  123. if (NULL == realPath) {
  124. // Nothing to do if the file doesn't exist.
  125. if (ENOENT == errno) {
  126. reset();
  127. return "";
  128. }
  129. // Something went wrong.
  130. throw std::runtime_error("Error checking file \"" + name + "\": " +
  131. getErrorText());
  132. }
  133. path.assign(realPath);
  134. free(realPath);
  135. #endif
  136. return path;
  137. }
  138. bool FileReference::exists() const {
  139. return fileExists;
  140. }
  141. bool FileReference::isDirectory() const {
  142. return fileIsDirectory;
  143. }
  144. std::string FileReference::getErrorText() {
  145. #ifdef _WIN32
  146. LPVOID winMsgBuf;
  147. DWORD lastError = GetLastError();
  148. FormatMessage(
  149. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  150. FORMAT_MESSAGE_FROM_SYSTEM |
  151. FORMAT_MESSAGE_IGNORE_INSERTS,
  152. NULL,
  153. lastError,
  154. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  155. (char *) &winMsgBuf,
  156. 0, NULL );
  157. std::string errMsg((char *) winMsgBuf);
  158. LocalFree(winMsgBuf);
  159. return errMsg;
  160. #else
  161. return strerror(errno);
  162. #endif
  163. }
  164. DirectoryReference::DirectoryReference(std::string dirName,
  165. bool (*dirFilter)(std::string)) :
  166. name(dirName),
  167. filter(dirFilter) {
  168. refresh();
  169. }
  170. void DirectoryReference::refresh() {
  171. // Clear any entries in this object.
  172. this->clear();
  173. #ifdef _WIN32
  174. HANDLE hDirList;
  175. WIN32_FIND_DATA dirListData;
  176. std::string searchString = FilePath::join({name, "*"});
  177. hDirList = FindFirstFile(searchString.c_str(), &dirListData);
  178. if (INVALID_HANDLE_VALUE == hDirList) {
  179. throw std::runtime_error("Error getting file list for \"" + name +
  180. "\": " + FileReference::getErrorText());
  181. }
  182. std::string tempName;
  183. while (INVALID_HANDLE_VALUE != hDirList) {
  184. tempName = FilePath::join({name, dirListData.cFileName});
  185. if ( (0 == filter) || (*filter)(dirListData.cFileName)) {
  186. emplace_back(tempName);
  187. }
  188. if (!FindNextFile(hDirList, &dirListData)) {
  189. FindClose(hDirList);
  190. hDirList = INVALID_HANDLE_VALUE;
  191. }
  192. }
  193. #else
  194. // Get new list.
  195. struct dirent **entries;
  196. int nEntries = scandir(name.c_str(), &entries, 0, 0);
  197. if (nEntries < 0) {
  198. throw std::runtime_error("Error getting file list for \"" + name +
  199. "\": " + FileReference::getErrorText());
  200. }
  201. // Create the FileReference objects.
  202. while (nEntries--) {
  203. std::string tempName;
  204. tempName = FilePath::join({name, entries[nEntries]->d_name});
  205. if ( (0 == filter) || (*filter)(entries[nEntries]->d_name)) {
  206. emplace_back(tempName);
  207. }
  208. free(entries[nEntries]);
  209. }
  210. free(entries);
  211. #endif
  212. }
  213. }