static VALUE dir_set_pos(VALUE self, VALUE v_pos){ NDirStruct* ptr; uintptr_t pos; Check_Type(v_pos, T_FIXNUM); Data_Get_Struct(self, NDirStruct, ptr); pos = FIX2LONG(v_pos); // Nothing to do if argument matches current position. if (pos != ptr->position){ uintptr_t i = 0; uintptr_t max; WIN32_FIND_DATA data; memset(&data, 0, sizeof(data)); // If argument is less than the current position then rewind the handle. if (pos < ptr->position){ FindClose(ptr->fhandle); ptr->position = pos; if(pos == 0) return pos; ptr->fhandle = FindFirstFileEx(ptr->path, FindExInfoBasic, &data, FindExSearchNameMatch, NULL, 0); if(ptr->fhandle == INVALID_HANDLE_VALUE) rb_raise_win_error("FindFirstFileEx", GetLastError()); else i++; } // Then fast forward the handle to the specified position. max = pos - ptr->position; for (; i < max; i++){ if(ptr->fhandle == INVALID_HANDLE_VALUE){ ptr->fhandle = FindFirstFileEx(ptr->path, FindExInfoBasic, &data, FindExSearchNameMatch, NULL, 0); if(ptr->fhandle == INVALID_HANDLE_VALUE) rb_raise_win_error("FindFirstFileEx", GetLastError()); } else{ if (!FindNextFile(ptr->fhandle, &data)){ DWORD errnum = GetLastError(); if (errnum == ERROR_NO_MORE_FILES) break; else rb_raise_win_error("FindNextFile", errnum); } } ptr->position++; } } return v_pos; }
bool WinFileSystem::recursiveFind(const FindInfo& findinfo, std::vector<String>& result) { WIN32_FIND_DATA ffd; String mask = File::concat(findinfo.path, UTEXT("*")); HANDLE hFind = FindFirstFileEx(mask.c_str(), FindExInfoBasic, &ffd, FindExSearchNameMatch, NULL, 0); if ( hFind == INVALID_HANDLE_VALUE ) { return true; } do { String name(ffd.cFileName); bool isdir = IS_SET(ffd.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY); if ( isdir ) { if ( name != UTEXT(".") && name != UTEXT("..") ) { FindInfo rfind; rfind.filemask = findinfo.filemask; rfind.path = File::concat(findinfo.path, name); find(rfind, result, true); } } } while ( FindNextFile(hFind, &ffd) != 0 ); FindClose(hFind); return true; }
static VALUE dir_s_foreach(VALUE klass, VALUE v_dir){ HANDLE fhandle; WIN32_FIND_DATA data; char* path; Check_Type(v_dir, T_STRING); memset(&data, 0, sizeof(data)); // Append *.* to base path since that will be used for reads, etc. path = (char*)ruby_xmalloc(RSTRING_LEN(v_dir) + strlen("/*.*") + 1); sprintf(path, "%s%s", RSTRING_PTR(v_dir), "/*.*"); fhandle = FindFirstFileEx(path, FindExInfoBasic, &data, FindExSearchNameMatch, NULL, 0); if (fhandle == INVALID_HANDLE_VALUE) rb_raise_win_error("FindFirstFileEx", GetLastError()); else rb_yield(rb_str_new2(data.cFileName)); while(FindNextFile(fhandle, &data)) rb_yield(rb_str_new2(data.cFileName)); FindClose(fhandle); return Qnil; }
bool WinFileSystem::find(const FindInfo& findinfo, std::vector<String>& result, bool recursive) { WIN32_FIND_DATA ffd; String mask = File::concat(findinfo.path, findinfo.filemask); HANDLE hFind = FindFirstFileEx(mask.c_str(), FindExInfoBasic, &ffd, FindExSearchNameMatch, NULL, 0); if ( hFind != INVALID_HANDLE_VALUE ) { do { String name(ffd.cFileName); if ( !IS_SET(ffd.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY) ) { result.push_back(File::concat(findinfo.path, name)); } } while ( FindNextFile(hFind, &ffd) != 0 ); DWORD dwError = GetLastError(); FindClose(hFind); if (dwError != ERROR_NO_MORE_FILES) return false; } return recursive ? recursiveFind(findinfo, result) : true; }
void ff::ClearTempSubDirectory() { #if !METRO_APP if (GetTempSubDirectory().empty()) { // don't clear the root temp path return; } #endif ff::String szFilter = ff::GetTempDirectory(); AppendPathTail(szFilter, String(L"*")); WIN32_FIND_DATA data; ZeroObject(data); HANDLE hFind = FindFirstFileEx(szFilter.c_str(), FindExInfoStandard, &data, FindExSearchNameMatch, nullptr, 0); for (BOOL bDone = FALSE; !bDone && hFind != INVALID_HANDLE_VALUE; bDone = !FindNextFile(hFind, &data)) { if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { ff::String szFile = ff::GetTempDirectory(); AppendPathTail(szFile, String(data.cFileName)); DeleteFile(szFile); } } if (hFind != INVALID_HANDLE_VALUE) { FindClose(hFind); } }
static VALUE dir_s_glob(VALUE klass, VALUE v_dir){ HANDLE fhandle; WIN32_FIND_DATA data; VALUE v_array; char* path; Check_Type(v_dir, T_STRING); memset(&data, 0, sizeof(data)); v_array = rb_ary_new(); path = RSTRING_PTR(v_dir); fhandle = FindFirstFileEx(path, FindExInfoBasic, &data, FindExSearchNameMatch, NULL, 0); if (fhandle == INVALID_HANDLE_VALUE) rb_raise_win_error("FindFirstFileEx", GetLastError()); else rb_ary_push(v_array, rb_str_new2(data.cFileName)); while(FindNextFile(fhandle, &data)) rb_ary_push(v_array, rb_str_new2(data.cFileName)); FindClose(fhandle); return v_array; }
std::vector<std::tstring> ContainerManager::GetAccountNames() const { std::vector<std::tstring> result; std::tstring path = AOManager::instance().getAOPrefsFolder(); path += _T("\\*"); WIN32_FIND_DATA findData; HANDLE hFind = FindFirstFileEx(path.c_str(), FindExInfoStandard, &findData, FindExSearchLimitToDirectories, NULL, 0); if (hFind != INVALID_HANDLE_VALUE) { do { if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (findData.cFileName[0] != NULL) && (findData.cFileName[0] != '.') && (std::tstring(findData.cFileName) != _T("Browser"))) { result.push_back(std::tstring(findData.cFileName)); } } while (FindNextFile(hFind, &findData)); FindClose(hFind); } return result; }
/* http://www.syuhitu.org/other/dir.html */ const char * vp_readdir(char *args) { vp_stack_t stack; char *dirname; char buf[1024]; WIN32_FIND_DATA fd; HANDLE h; VP_RETURN_IF_FAIL(vp_stack_from_args(&stack, args)); VP_RETURN_IF_FAIL(vp_stack_pop_str(&stack, &dirname)); snprintf(buf, sizeof(buf), "%s\\*", dirname); /* Get handle. */ h = FindFirstFileEx(buf, FindExInfoStandard, &fd, FindExSearchNameMatch, NULL, 0 ); if (h == INVALID_HANDLE_VALUE) { return vp_stack_return_error(&_result, "FindFirstFileEx() error: %s", GetLastError()); } do { snprintf(buf, sizeof(buf), "%s/%s", dirname, fd.cFileName); vp_stack_push_str(&_result, buf); } while (FindNextFile(h, &fd)); FindClose(h); return vp_stack_return(&_result); }
DirectoryIterator::DirectoryIterator(path const& p, std::string const& filter) : privdata(new PrivData) { WIN32_FIND_DATA data; privdata->h = FindFirstFileEx((p/(filter.empty() ? "*.*" : filter)).c_str(), find_info_level(), &data, FindExSearchNameMatch, nullptr, 0); if (privdata->h == INVALID_HANDLE_VALUE) { privdata.reset(); return; } value = ConvertW(data.cFileName); while (value[0] == '.' && (value[1] == 0 || value[1] == '.')) ++*this; }
bool CLocalFileSystem::BeginFindFiles(wxString path, bool dirs_only) { EndFindFiles(); m_dirs_only = dirs_only; #ifdef __WXMSW__ if (path.Last() != '/' && path.Last() != '\\') { m_find_path = path + _T("\\"); path += _T("\\*"); } else { m_find_path = path; path += '*'; } m_hFind = FindFirstFileEx(path, FindExInfoStandard, &m_find_data, dirs_only ? FindExSearchLimitToDirectories : FindExSearchNameMatch, 0, 0); if (m_hFind == INVALID_HANDLE_VALUE) { m_found = false; return false; } m_found = true; return true; #else if (path != _T("/") && path.Last() == '/') path.RemoveLast(); const wxCharBuffer s = path.fn_str(); m_dir = opendir(s); if (!m_dir) return false; const wxCharBuffer p = path.fn_str(); const int len = strlen(p); m_raw_path = new char[len + 2048 + 2]; m_buffer_length = len + 2048 + 2; strcpy(m_raw_path, p); if (len > 1) { m_raw_path[len] = '/'; m_file_part = m_raw_path + len + 1; } else m_file_part = m_raw_path + len; return true; #endif }
static VALUE dir_read(VALUE self){ NDirStruct* ptr; WIN32_FIND_DATA data; Data_Get_Struct(self, NDirStruct, ptr); memset(&data, 0, sizeof(data)); if(ptr->position == 0){ ptr->fhandle = FindFirstFileEx(ptr->path, FindExInfoBasic, &data, FindExSearchNameMatch, NULL, 0); if(ptr->fhandle == INVALID_HANDLE_VALUE) rb_raise_win_error("FindFirstFileEx", GetLastError()); } else{ if(ptr->fhandle == INVALID_HANDLE_VALUE){ ptr->fhandle = FindFirstFileEx(ptr->path, FindExInfoBasic, &data, FindExSearchNameMatch, NULL, 0); } else{ if(!FindNextFile(ptr->fhandle, &data)){ int errnum = GetLastError(); if(errnum == ERROR_NO_MORE_FILES){ return Qnil; } else{ FindClose(ptr->fhandle); rb_raise_win_error("FindNextFile", errnum); } } } } ptr->position++; return rb_str_new2(data.cFileName); }
BOOL ProcessDirectories(LPTSTR Path) { WIN32_FIND_DATA FindFile; TCHAR SearchPath[MAX_PATH]; HANDLE SearchHandle; BOOL More; if(!BeSilent) { _tprintf (_T("Processing %s ...\n"), Path); } _tcscpy (SearchPath, Path); _tcscat (SearchPath, _T("\\*.*")); SearchHandle = FindFirstFileEx (SearchPath, FindExInfoStandard, &FindFile, FindExSearchLimitToDirectories, NULL, 0); if (SearchHandle != INVALID_HANDLE_VALUE) { More = TRUE; while (More) { if ((FindFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (_tcscmp (FindFile.cFileName, _T(".")) != 0) && (_tcscmp (FindFile.cFileName, _T("..")) != 0) && (_tcscmp (FindFile.cFileName, _T("CVS")) != 0) && (_tcscmp (FindFile.cFileName, _T(".svn")) != 0)) { _tcscpy (SearchPath, Path); _tcscat (SearchPath, _T("\\")); _tcscat (SearchPath, FindFile.cFileName); if (!ProcessDirectories (SearchPath)) return FALSE; if (!ProcessFiles (SearchPath)) return FALSE; } More = FindNextFile (SearchHandle, &FindFile); } FindClose (SearchHandle); } return TRUE; }
// 'Corrects' the security on a file by taking ownership of it and giving the current user full control // For directories these will do a complete recursive correction. static void CorrectSecurity(TCHAR *f, DWORD attrib, BOOL takeownership, PSID sid, PACL acl, BOOL oneVolumeOnly) { BY_HANDLE_FILE_INFORMATION info; if (attrib != INVALID_FILE_ATTRIBUTES) { DWORD err; if (sid && takeownership) { err = SetNamedSecurityInfo(f, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, sid, NULL, NULL, NULL); if (err != ERROR_SUCCESS) { LogFileError(TEXT("SetNamedSecurityInfo (change owner)"), f, err); } } if (sid && acl) { err = SetNamedSecurityInfo(f, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, acl, NULL); if (err != ERROR_SUCCESS) { LogFileError(TEXT("SetNamedSecurityInfo (change DACL)"), f, err); } } if ((attrib & FILE_ATTRIBUTE_DIRECTORY) && !(oneVolumeOnly && FileChangesVolume(f))) { // Recursively go through the directories WIN32_FIND_DATA ffd; TCHAR full[BIG_PATH+5], *file = copyStr(f); HANDLE hFind; DWORD dwError; DWORD len = _tcslen(file); while (len > 0 && file[len-1] == L'\\') file[--len] = 0; file[len ] = TEXT('\\'); file[len+1] = TEXT('*'); file[len+2] = 0; hFind = FindFirstFileEx(file, FindExInfoBasic, &ffd, FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH); if (hFind == INVALID_HANDLE_VALUE) { dwError = GetLastError(); if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_ACCESS_DENIED) LogFileError(TEXT("FindFirstFileEx in CorrectSecurity failed for"), file, dwError); } else { do { if (_tcscmp(ffd.cFileName, TEXT("..")) == 0 || _tcscmp(ffd.cFileName, TEXT(".")) == 0) continue; CorrectSecurity(makeFullPath(f, ffd.cFileName, full), ffd.dwFileAttributes, takeownership, sid, acl, oneVolumeOnly); } while (FindNextFile(hFind, &ffd) != 0); dwError = GetLastError(); if (dwError != ERROR_NO_MORE_FILES) LogError(TEXT("FindNextFile in CorrectSecurity"), dwError); FindClose(hFind); } free(file); } if (attrib & FILE_ATTRIBUTE_READONLY) { // Remove the read-only attribute SetFileAttributes(f, attrib&!FILE_ATTRIBUTE_READONLY); } } }
bool ff::DirectoryExists(StringRef path, WIN32_FIND_DATA *pFindData) { String szCheckPath = CanonicalizePath(path, true); WIN32_FIND_DATA data; pFindData = pFindData ? pFindData : &data; HANDLE hFind = FindFirstFileEx(szCheckPath.c_str(), FindExInfoStandard, pFindData, FindExSearchLimitToDirectories, nullptr, 0); if (hFind != INVALID_HANDLE_VALUE) { FindClose(hFind); return (pFindData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; } return false; }
static BOOL find_portable_dir(LPCWSTR base, LPWSTR *result, BOOL *existing) { WCHAR buf[4*MAX_PATH] = {0}; _snwprintf_s(buf, 4*MAX_PATH, _TRUNCATE, L"%s\\calibre-portable.exe", base); *existing = true; if (file_exists(buf)) { *result = _wcsdup(base); if (*result == NULL) { show_error(L"Out of memory"); return false; } return true; } WIN32_FIND_DATA fdFile; HANDLE hFind = NULL; _snwprintf_s(buf, 4*MAX_PATH, _TRUNCATE, L"%s\\*", base); if((hFind = FindFirstFileEx(buf, FindExInfoStandard, &fdFile, FindExSearchLimitToDirectories, NULL, 0)) != INVALID_HANDLE_VALUE) { do { if(is_dots(fdFile.cFileName)) continue; if(fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { _snwprintf_s(buf, 4*MAX_PATH, _TRUNCATE, L"%s\\%s\\calibre-portable.exe", base, fdFile.cFileName); if (file_exists(buf)) { *result = _wcsdup(buf); if (*result == NULL) { show_error(L"Out of memory"); return false; } PathRemoveFileSpec(*result); FindClose(hFind); return true; } } } while(FindNextFile(hFind, &fdFile)); FindClose(hFind); } *existing = false; _snwprintf_s(buf, 4*MAX_PATH, _TRUNCATE, L"%s\\Calibre Portable", base); if (!CreateDirectory(buf, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { show_last_error(L"Failed to create Calibre Portable folder"); return false; } *result = _wcsdup(buf); if (*result == NULL) { show_error(L"Out of memory"); return false; } return true; }
std::unique_ptr<osd::directory::entry> osd_stat(const std::string &path) { // convert the path to TCHARs std::unique_ptr<TCHAR, void (*)(void *)> const t_path(tstring_from_utf8(path.c_str()), &osd_free); if (!t_path) return nullptr; // is this path a root directory (e.g. - C:)? WIN32_FIND_DATA find_data; std::memset(&find_data, 0, sizeof(find_data)); if (isalpha(path[0]) && (path[1] == ':') && (path[2] == '\0')) { // need to do special logic for root directories if (!GetFileAttributesEx(t_path.get(), GetFileExInfoStandard, &find_data.dwFileAttributes)) find_data.dwFileAttributes = INVALID_FILE_ATTRIBUTES; } else { // attempt to find the first file HANDLE find = FindFirstFileEx(t_path.get(), FindExInfoStandard, &find_data, FindExSearchNameMatch, nullptr, 0); if (find == INVALID_HANDLE_VALUE) return nullptr; FindClose(find); } // create an osd::directory::entry; be sure to make sure that the caller can // free all resources by just freeing the resulting osd::directory::entry osd::directory::entry *result; try { result = reinterpret_cast<osd::directory::entry *>(::operator new(sizeof(*result) + path.length() + 1)); } catch (...) { return nullptr; } new (result) osd::directory::entry; strcpy(((char *) result) + sizeof(*result), path.c_str()); result->name = ((char *) result) + sizeof(*result); result->type = win_attributes_to_entry_type(find_data.dwFileAttributes); result->size = find_data.nFileSizeLow | ((UINT64) find_data.nFileSizeHigh << 32); result->last_modified = win_time_point_from_filetime(&find_data.ftLastWriteTime); return std::unique_ptr<osd::directory::entry>(result); }
static int posix_helper(const wchar_t *dirpath) { int count = 0; HANDLE hSearch; WIN32_FIND_DATA fd; const size_t origDirPathLength = wcslen(dirpath); wchar_t appendedPath[MAX_PATH]; wcscpy(appendedPath, dirpath); wcscat(appendedPath, L"\\*"); #ifndef Q_OS_WINRT hSearch = FindFirstFile(appendedPath, &fd); #else hSearch = FindFirstFileEx(appendedPath, FindExInfoStandard, &fd, FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH); #endif appendedPath[origDirPathLength] = 0; if (hSearch == INVALID_HANDLE_VALUE) { qWarning("FindFirstFile failed"); return count; } do { if (!(fd.cFileName[0] == L'.' && fd.cFileName[1] == 0) && !(fd.cFileName[0] == L'.' && fd.cFileName[1] == L'.' && fd.cFileName[2] == 0)) { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { wcscat(appendedPath, L"\\"); wcscat(appendedPath, fd.cFileName); count += posix_helper(appendedPath); appendedPath[origDirPathLength] = 0; } else { ++count; } } } while (FindNextFile(hSearch, &fd)); FindClose(hSearch); return count; }
bool ff::GetDirectoryContents(StringRef path, Vector<String> &dirs, Vector<String> &files, Vector<FILETIME> *fileTimes) { dirs.Clear(); files.Clear(); if (fileTimes) { fileTimes->Clear(); } String szFilter = CanonicalizePath(path, true); assertRetVal(szFilter.size(), false); AppendPathTail(szFilter, String(L"*")); WIN32_FIND_DATA data; ZeroObject(data); HANDLE hFind = FindFirstFileEx(szFilter.c_str(), FindExInfoStandard, &data, FindExSearchNameMatch, nullptr, 0); for (BOOL bDone = FALSE; !bDone && hFind != INVALID_HANDLE_VALUE; bDone = !FindNextFile(hFind, &data)) { if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { files.Push(String(data.cFileName)); if (fileTimes) { fileTimes->Push(data.ftLastWriteTime); } } else if (wcscmp(data.cFileName, L".") && wcscmp(data.cFileName, L"..")) { dirs.Push(String(data.cFileName)); } } if (hFind != INVALID_HANDLE_VALUE) { FindClose(hFind); } return hFind != INVALID_HANDLE_VALUE; }
/*! \internal */ void QFileSystemIteratorPrivate::pushSubDirectory(const QByteArray &path) { /* if (iteratorFlags & QFileSystemIterator::FollowSymlinks) { if (fileInfo.filePath() != path) fileInfo.setFile(path); if (fileInfo.isSymLink()) { visitedLinks << fileInfo.canonicalFilePath(); } else { visitedLinks << fileInfo.absoluteFilePath(); } } */ #ifdef Q_OS_WIN wchar_t szSearchPath[MAX_PATH]; QString::fromLatin1(path).toWCharArray(szSearchPath); wcscat(szSearchPath, L"\\*"); #ifndef Q_OS_WINRT HANDLE dir = FindFirstFile(szSearchPath, &m_fileSearchResult); #else HANDLE dir = FindFirstFileEx(szSearchPath, FindExInfoStandard, &m_fileSearchResult, FindExSearchLimitToDirectories, NULL, FIND_FIRST_EX_LARGE_FETCH); #endif m_bFirstSearchResult = true; #else DIR *dir = ::opendir(path.constData()); //m_entry = ::readdir(dir); //while (m_entry && isDotOrDotDot(m_entry->d_name)) // m_entry = ::readdir(m_dirStructs.top()); #endif m_dirStructs.append(dir); m_dirPaths.append(path); m_entry = 0; if (filters & QDir::Dirs) m_nextDirShown = ShowDir; else m_nextDirShown = DontShowDir; m_currentDirShown = DontShowDir; }
void CPictureRing::AddTestPicture(wchar_t* dirName, int fileNum, double k) { #ifdef WIN32 CCVPictureFrame* photo; double photoDepth = 15.0; int i; WIN32_FIND_DATA fd; HANDLE h; wchar_t fileName[512]; int len = wcslen(dirName); wcscpy(fileName, dirName); wcscat(fileName, L"*.jpg"); h = FindFirstFileEx(fileName, FindExInfoStandard, &fd, FindExSearchNameMatch, NULL, 0); if(h == INVALID_HANDLE_VALUE) return; i = 0; do { if(!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { i++; photo = new CCVPictureFrame(); photo->Init(); photo->picture->SetColor4(1.0f, 1.0f, 1.0f, 1.0f); photo->frame->SetAlpha(0.0f); wcscpy(fileName, dirName); wcscat(fileName, fd.cFileName); photo->picture->OpenFile(fileName, pictureSize * k); photo->SetCardMode(true); photo->SetSize(pictureSize, pictureSize, pictureDepth); AddObject(photo); } } while(FindNextFile(h, &fd) && i < fileNum); FindClose(h); #endif }
std::vector<std::wstring> GetFileList(const std::wstring& pattern, bool fullPaths) { std::wstring directory; if (fullPaths) directory = GetDirPart(pattern); WIN32_FIND_DATA findData; HANDLE hFindFile = FindFirstFileEx(pattern.c_str(), FindExInfoStandard, &findData, FindExSearchNameMatch, NULL, 0); std::vector<std::wstring> result; if (hFindFile != INVALID_HANDLE_VALUE) { do { result.emplace_back(directory + findData.cFileName); } while (FindNextFile(hFindFile, &findData)); FindClose(hFindFile); } return result; }
bool QFileSystemModelEx::hasSubfolders(const QString &path) { if(s_findFirstFileExInfoLevel == INT_MAX) { const lamexp_os_version_t &osVersionNo = lamexp_get_os_version(); s_findFirstFileExInfoLevel = (osVersionNo >= lamexp_winver_win70) ? FindExInfoBasic : FindExInfoStandard; } WIN32_FIND_DATAW findData; bool bChildren = false; HANDLE h = FindFirstFileEx(QWCHAR(QDir::toNativeSeparators(path + "/*")), ((FINDEX_INFO_LEVELS)s_findFirstFileExInfoLevel), &findData, FindExSearchLimitToDirectories, NULL, 0); if(h != INVALID_HANDLE_VALUE) { if(NO_DOT_OR_DOTDOT(findData.cFileName)) { bChildren = IS_DIR(findData.dwFileAttributes); } while((!bChildren) && FindNextFile(h, &findData)) { if(NO_DOT_OR_DOTDOT(findData.cFileName)) { bChildren = IS_DIR(findData.dwFileAttributes); } } FindClose(h); } else { DWORD err = GetLastError(); if((err == ERROR_NOT_SUPPORTED) || (err == ERROR_INVALID_PARAMETER)) { qWarning("FindFirstFileEx failed with error code #%u", err); } } return bChildren; }
std::vector<Path> QueryDirectory(const Path &path, const Pred& predicate) { std::vector<Path> result; auto pathStr = path.ToString() + L"\\*"; WIN32_FIND_DATA data; auto handle = FindFirstFileEx( pathStr.c_str(), FindExInfoBasic, &data, FindExSearchNameMatch, nullptr, 0); if (handle == INVALID_HANDLE_VALUE) { return std::vector<Path>(); } if (predicate(data)) { result.push_back(Path(std::wstring(data.cFileName))); } while (FindNextFile(handle, &data)) { if (predicate(data)) { result.push_back(Path(std::wstring(data.cFileName))); } } FindClose(handle); return result; }
// GetFilesNoRecurse //------------------------------------------------------------------------------ /*static*/ void FileIO::GetFilesNoRecurse( const char * path, const char * wildCard, Array< AString > * results ) { AStackString< 256 > pathCopy( path ); PathUtils::EnsureTrailingSlash( pathCopy ); const uint32_t baseLength = pathCopy.GetLength(); #if defined( __WINDOWS__ ) pathCopy += '*'; WIN32_FIND_DATA findData; //HANDLE hFind = FindFirstFile( pathCopy.Get(), &findData ); HANDLE hFind = FindFirstFileEx( pathCopy.Get(), FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, 0 ); if ( hFind == INVALID_HANDLE_VALUE) { return; } do { if ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { continue; } if ( PathUtils::IsWildcardMatch( wildCard, findData.cFileName ) ) { pathCopy.SetLength( baseLength ); pathCopy += findData.cFileName; results->Append( pathCopy ); } } while ( FindNextFile( hFind, &findData ) != 0 ); FindClose( hFind ); #elif defined( __LINUX__ ) || defined( __APPLE__ ) DIR * dir = opendir( pathCopy.Get() ); if ( dir == nullptr ) { return; } for ( ;; ) { dirent * entry = readdir( dir ); if ( entry == nullptr ) { break; // no more entries } // dir? if ( ( entry->d_type & DT_DIR ) == DT_DIR ) { // ignore dirs continue; } // file - does it match wildcard? if ( PathUtils::IsWildcardMatch( wildCard, entry->d_name ) ) { pathCopy.SetLength( baseLength ); pathCopy += entry->d_name; results->Append( pathCopy ); } } closedir( dir ); #else #error Unknown platform #endif }
bool FileUtils::removeDirectory(const std::string& path) { if (path.size() > 0 && path[path.size() - 1] != '/') { CCLOGERROR("Fail to remove directory, path must termniate with '/': %s", path.c_str()); return false; } // Remove downloaded files #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) std::wstring wpath = std::wstring(path.begin(), path.end()); std::wstring files = wpath + L"*.*"; WIN32_FIND_DATA wfd; HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); bool ret=true; if (search!=INVALID_HANDLE_VALUE) { BOOL find=true; while (find) { //. .. if(wfd.cFileName[0]!='.') { std::wstring temp = wpath + wfd.cFileName; if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { temp += '/'; ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end())); } else { SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL); ret = ret && DeleteFile(temp.c_str()); } } find = FindNextFile(search, &wfd); } FindClose(search); } if (ret && RemoveDirectory(wpath.c_str())) { return true; } return false; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) std::string command = "cmd /c rd /s /q "; // Path may include space. command += "\"" + path + "\""; if (WinExec(command.c_str(), SW_HIDE) > 31) return true; else return false; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) return false; else return true; #else std::string command = "rm -r "; // Path may include space. command += "\"" + path + "\""; if (system(command.c_str()) >= 0) return true; else return false; #endif }
INT_PTR CALLBACK CDialogPackage::SelectFolderDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { EnableThemeDialogTexture(hWnd, ETDT_ENABLETAB); c_Dialog->SetDialogFont(hWnd); std::wstring* existingPath = (std::wstring*)lParam; SetWindowLongPtr(hWnd, GWLP_USERDATA, lParam); *existingPath += L'*'; WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFileEx(existingPath->c_str(), FindExInfoStandard, &fd, FindExSearchNameMatch, NULL, 0); existingPath->pop_back(); if (hFind != INVALID_HANDLE_VALUE) { const WCHAR* folder = PathFindFileName(existingPath->c_str()); HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_RADIO); std::wstring text = L"Add folder from "; text.append(folder, wcslen(folder) - 1); text += L':'; SetWindowText(item, text.c_str()); Button_SetCheck(item, BST_CHECKED); item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO); do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY && !(fd.cFileName[0] == L'.' && (!fd.cFileName[1] || fd.cFileName[1] == L'.' && !fd.cFileName[2])) && wcscmp(fd.cFileName, L"Backup") != 0 && wcscmp(fd.cFileName, L"@Backup") != 0) { ComboBox_InsertString(item, -1, fd.cFileName); } } while (FindNextFile(hFind, &fd)); ComboBox_SetCurSel(item, 0); FindClose(hFind); } } break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_PACKAGESELECTFOLDER_EXISTING_RADIO: { HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO); EnableWindow(item, TRUE); int sel = ComboBox_GetCurSel(item); item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT); EnableWindow(item, FALSE); item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON); EnableWindow(item, FALSE); item = GetDlgItem(hWnd, IDOK); EnableWindow(item, sel != -1); } break; case IDC_PACKAGESELECTFOLDER_CUSTOM_RADIO: { HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_COMBO); EnableWindow(item, FALSE); item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT); EnableWindow(item, TRUE); item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON); EnableWindow(item, TRUE); SendMessage(hWnd, WM_COMMAND, MAKEWPARAM(IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT, EN_CHANGE), 0); } break; case IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT: if (HIWORD(wParam) == EN_CHANGE) { WCHAR buffer[MAX_PATH]; int len = Edit_GetText((HWND)lParam, buffer, MAX_PATH); // Disable Add button if invalid directory DWORD attributes = GetFileAttributes(buffer); BOOL state = (attributes != INVALID_FILE_ATTRIBUTES && attributes & FILE_ATTRIBUTE_DIRECTORY); EnableWindow(GetDlgItem(hWnd, IDOK), state); } break; case IDC_PACKAGESELECTFOLDER_CUSTOMBROWSE_BUTTON: { WCHAR buffer[MAX_PATH]; BROWSEINFO bi = {0}; bi.hwndOwner = hWnd; bi.ulFlags = BIF_USENEWUI | BIF_NONEWFOLDERBUTTON | BIF_RETURNONLYFSDIRS; PIDLIST_ABSOLUTE pidl = SHBrowseForFolder(&bi); if (pidl && SHGetPathFromIDList(pidl, buffer)) { HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT); SetWindowText(item, buffer); CoTaskMemFree(pidl); } } break; case IDOK: { WCHAR buffer[MAX_PATH]; HWND item = GetDlgItem(hWnd, IDC_PACKAGESELECTFOLDER_EXISTING_RADIO); bool existing = Button_GetCheck(item) == BST_CHECKED; item = GetDlgItem(hWnd, existing ? IDC_PACKAGESELECTFOLDER_EXISTING_COMBO : IDC_PACKAGESELECTFOLDER_CUSTOM_EDIT); GetWindowText(item, buffer, _countof(buffer)); std::wstring* result = (std::wstring*)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (existing) { *result += buffer; } else { *result = buffer; } *result += L'\\'; EndDialog(hWnd, 1); } } break; case WM_CLOSE: EndDialog(hWnd, 0); break; default: return FALSE; } return TRUE; }
bool CDialogPackage::AddFolderToPackage(const std::wstring& path, std::wstring base, const WCHAR* zipPrefix) { std::wstring currentPath = path + base; currentPath += L'*'; WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFileEx( currentPath.c_str(), FindExInfoStandard, &fd, FindExSearchNameMatch, NULL, 0); if (hFind == INVALID_HANDLE_VALUE) { return false; } currentPath.pop_back(); // Remove * bool result = true; bool filesAdded = false; std::list<std::wstring> folders; do { if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) { // Ignore hidden files and folders continue; } if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (!(fd.cFileName[0] == L'.' && (!fd.cFileName[1] || fd.cFileName[1] == L'.' && !fd.cFileName[2]))) { folders.push_back(fd.cFileName); } } else { std::wstring filePath = currentPath + fd.cFileName; std::wstring zipPath = zipPrefix; zipPath.append(filePath, path.length(), filePath.length() - path.length()); result = AddFileToPackage(filePath.c_str(), zipPath.c_str()); if (!result) { std::wstring error = L"Error adding file:\n"; error += filePath; error += L"\n\nClick OK to close Packager."; MessageBox(m_Window, error.c_str(), L"Rainmeter Skin Packager", MB_OK | MB_ICONERROR); break; } filesAdded = true; } } while (FindNextFile(hFind, &fd)); FindClose(hFind); if (result) { if (!filesAdded && folders.empty()) { // Add directory entry if folder is empty. std::wstring zipPath = zipPrefix; zipPath.append(currentPath, path.length(), currentPath.length() - path.length()); AddFileToPackage(NULL, zipPath.c_str()); } std::list<std::wstring>::const_iterator iter = folders.begin(); for ( ; iter != folders.end(); ++iter) { std::wstring newBase = base + (*iter); newBase += L'\\'; result = AddFolderToPackage(path, newBase, zipPrefix); if (!result) break; } } return result; }
bool update() { writeLog(L"Update started.."); wstring updDir = L"tupdates\\ready"; deque<wstring> dirs; dirs.push_back(updDir); deque<wstring> from, to, forcedirs; do { wstring dir = dirs.front(); dirs.pop_front(); wstring toDir = exeDir; if (dir.size() > updDir.size() + 1) { toDir += (dir.substr(updDir.size() + 1) + L"\\"); forcedirs.push_back(toDir); writeLog(L"Parsing dir '" + toDir + L"' in update tree.."); } WIN32_FIND_DATA findData; HANDLE findHandle = FindFirstFileEx((dir + L"\\*").c_str(), FindExInfoStandard, &findData, FindExSearchNameMatch, 0, 0); if (findHandle == INVALID_HANDLE_VALUE) { DWORD errorCode = GetLastError(); if (errorCode == ERROR_PATH_NOT_FOUND) { // no update is ready return true; } writeLog(L"Error: failed to find update files :("); updateError(L"Failed to find update files", errorCode); delFolder(); return false; } do { if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (findData.cFileName != wstring(L".") && findData.cFileName != wstring(L"..")) { dirs.push_back(dir + L"\\" + findData.cFileName); writeLog(L"Added dir '" + dir + L"\\" + findData.cFileName + L"' in update tree.."); } } else { wstring fname = dir + L"\\" + findData.cFileName; wstring tofname = exeDir + fname.substr(updDir.size() + 1); if (equal(tofname, exeName)) { // bad update - has Updater.exe - delete all dir writeLog(L"Error: bad update, has Updater.exe! '" + tofname + L"' equal '" + exeName + L"'"); delFolder(); return false; } from.push_back(fname); to.push_back(tofname); writeLog(L"Added file '" + fname + L"' to be copied to '" + tofname + L"'"); } } while (FindNextFile(findHandle, &findData)); DWORD errorCode = GetLastError(); if (errorCode && errorCode != ERROR_NO_MORE_FILES) { // everything is found writeLog(L"Error: failed to find next update file :("); updateError(L"Failed to find next update file", errorCode); delFolder(); return false; } FindClose(findHandle); } while (!dirs.empty()); for (size_t i = 0; i < forcedirs.size(); ++i) { wstring forcedir = forcedirs[i]; writeLog(L"Forcing dir '" + forcedir + L"'.."); if (!forcedir.empty() && !CreateDirectory(forcedir.c_str(), NULL)) { DWORD errorCode = GetLastError(); if (errorCode && errorCode != ERROR_ALREADY_EXISTS) { writeLog(L"Error: failed to create dir '" + forcedir + L"'.."); updateError(L"Failed to create directory", errorCode); delFolder(); return false; } writeLog(L"Already exists!"); } } for (size_t i = 0; i < from.size(); ++i) { wstring fname = from[i], tofname = to[i]; BOOL copyResult; do { writeLog(L"Copying file '" + fname + L"' to '" + tofname + L"'.."); int copyTries = 0; do { copyResult = CopyFile(fname.c_str(), tofname.c_str(), FALSE); if (copyResult == FALSE) { ++copyTries; Sleep(100); } else { break; } } while (copyTries < 30); if (copyResult == FALSE) { writeLog(L"Error: failed to copy, asking to retry.."); WCHAR errMsg[2048]; wsprintf(errMsg, L"Failed to update Telegram :(\n%s is not accessible.", tofname); if (MessageBox(0, errMsg, L"Update error!", MB_ICONERROR | MB_RETRYCANCEL) != IDRETRY) { delFolder(); return false; } } } while (copyResult == FALSE); } writeLog(L"Update succeed! Clearing folder.."); delFolder(); return true; }
// GetFilesRecurse //------------------------------------------------------------------------------ /*static*/ void FileIO::GetFilesRecurseEx( AString & pathCopy, const Array< AString > * patterns, Array< FileInfo > * results ) { const uint32_t baseLength = pathCopy.GetLength(); #if defined( __WINDOWS__ ) pathCopy += '*'; // don't want to use wildcard to filter folders // recurse into directories WIN32_FIND_DATA findData; HANDLE hFind = FindFirstFileEx( pathCopy.Get(), FindExInfoBasic, &findData, FindExSearchLimitToDirectories, nullptr, 0 ); if ( hFind == INVALID_HANDLE_VALUE) { return; } do { if ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { // ignore magic '.' and '..' folders // (don't need to check length of name, as all names are at least 1 char // which means index 0 and 1 are valid to access) if ( findData.cFileName[ 0 ] == '.' && ( ( findData.cFileName[ 1 ] == '.' ) || ( findData.cFileName[ 1 ] == '\000' ) ) ) { continue; } pathCopy.SetLength( baseLength ); pathCopy += findData.cFileName; pathCopy += NATIVE_SLASH; GetFilesRecurseEx( pathCopy, patterns, results ); } } while ( FindNextFile( hFind, &findData ) != 0 ); FindClose( hFind ); // do files in this directory pathCopy.SetLength( baseLength ); pathCopy += '*'; hFind = FindFirstFileEx( pathCopy.Get(), FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, 0 ); if ( hFind == INVALID_HANDLE_VALUE) { return; } do { if ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { continue; } if ( IsMatch( patterns, findData.cFileName ) ) { pathCopy.SetLength( baseLength ); pathCopy += findData.cFileName; if ( results->GetSize() == results->GetCapacity() ) { results->SetCapacity( results->GetSize() * 2 ); } results->SetSize( results->GetSize() + 1 ); FileInfo & newInfo = results->Top(); newInfo.m_Name = pathCopy; newInfo.m_Attributes = findData.dwFileAttributes; newInfo.m_LastWriteTime = (uint64_t)findData.ftLastWriteTime.dwLowDateTime | ( (uint64_t)findData.ftLastWriteTime.dwHighDateTime << 32 ); newInfo.m_Size = (uint64_t)findData.nFileSizeLow | ( (uint64_t)findData.nFileSizeHigh << 32 ); } } while ( FindNextFile( hFind, &findData ) != 0 ); FindClose( hFind ); #elif defined( __LINUX__ ) || defined( __APPLE__ ) DIR * dir = opendir( pathCopy.Get() ); if ( dir == nullptr ) { return; } for ( ;; ) { dirent * entry = readdir( dir ); if ( entry == nullptr ) { break; // no more entries } // dir? if ( ( entry->d_type & DT_DIR ) == DT_DIR ) { // ignore . and .. if ( entry->d_name[ 0 ] == '.' ) { if ( ( entry->d_name[ 1 ] == 0 ) || ( ( entry->d_name[ 1 ] == '.' ) && ( entry->d_name[ 2 ] == 0 ) ) ) { continue; } } // regular dir pathCopy.SetLength( baseLength ); pathCopy += entry->d_name; pathCopy += NATIVE_SLASH; GetFilesRecurseEx( pathCopy, patterns, results ); continue; } // file - does it match wildcard? if ( IsMatch( patterns, entry->d_name ) ) { pathCopy.SetLength( baseLength ); pathCopy += entry->d_name; if ( results->GetSize() == results->GetCapacity() ) { results->SetCapacity( results->GetSize() * 2 ); } results->SetSize( results->GetSize() + 1 ); FileInfo & newInfo = results->Top(); newInfo.m_Name = pathCopy; // get additional info struct stat info; VERIFY( stat( pathCopy.Get(), &info ) == 0 ); newInfo.m_Attributes = info.st_mode; #if defined( __APPLE__ ) newInfo.m_LastWriteTime = ( ( (uint64_t)info.st_mtimespec.tv_sec * 1000000000ULL ) + (uint64_t)info.st_mtimespec.tv_nsec ); #else newInfo.m_LastWriteTime = ( ( (uint64_t)info.st_mtim.tv_sec * 1000000000ULL ) + (uint64_t)info.st_mtim.tv_nsec ); #endif newInfo.m_Size = info.st_size; } } closedir( dir ); #else #error Unknown platform #endif }
int recursive_dir(u8 *filedir, int filedirsz) { int plen, namelen, ret = -1; #ifdef WIN32 static int winnt = -1; OSVERSIONINFO osver; WIN32_FIND_DATA wfd; HANDLE hFind = INVALID_HANDLE_VALUE; if(winnt < 0) { osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osver); if(osver.dwPlatformId >= VER_PLATFORM_WIN32_NT) { winnt = 1; } else { winnt = 0; } } plen = strlen(filedir); if((plen + 4) >= filedirsz) goto quit; strcpy(filedir + plen, "\\*.*"); plen++; if(winnt) { // required to avoid problems with Vista and Windows7! hFind = FindFirstFileEx(filedir, FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); } else { hFind = FindFirstFile(filedir, &wfd); } if(hFind == INVALID_HANDLE_VALUE) goto quit; do { if(!strcmp(wfd.cFileName, ".") || !strcmp(wfd.cFileName, "..")) continue; namelen = strlen(wfd.cFileName); if((plen + namelen) >= filedirsz) goto quit; //strcpy(filedir + plen, wfd.cFileName); memcpy(filedir + plen, wfd.cFileName, namelen); filedir[plen + namelen] = 0; if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(recursive_dir(filedir, filedirsz) < 0) goto quit; } else { add_files(filedir, wfd.nFileSizeLow, NULL); } } while(FindNextFile(hFind, &wfd)); ret = 0; quit: if(hFind != INVALID_HANDLE_VALUE) FindClose(hFind); #else struct stat xstat; struct dirent **namelist; int n, i; n = scandir(filedir, &namelist, NULL, NULL); if(n < 0) { if(stat(filedir, &xstat) < 0) { fprintf(stderr, "**** %s", filedir); STD_ERR; } add_files(filedir, xstat.st_size, NULL); return(0); } plen = strlen(filedir); if((plen + 1) >= filedirsz) goto quit; strcpy(filedir + plen, "/"); plen++; for(i = 0; i < n; i++) { if(!strcmp(namelist[i]->d_name, ".") || !strcmp(namelist[i]->d_name, "..")) continue; namelen = strlen(namelist[i]->d_name); if((plen + namelen) >= filedirsz) goto quit; //strcpy(filedir + plen, namelist[i]->d_name); memcpy(filedir + plen, namelist[i]->d_name, namelen); filedir[plen + namelen] = 0; if(stat(filedir, &xstat) < 0) { fprintf(stderr, "**** %s", filedir); STD_ERR; } if(S_ISDIR(xstat.st_mode)) { if(recursive_dir(filedir, filedirsz) < 0) goto quit; } else { add_files(filedir, xstat.st_size, NULL); } free(namelist[i]); } ret = 0; quit: for(; i < n; i++) free(namelist[i]); free(namelist); #endif filedir[plen - 1] = 0; return(ret); }