int enum_files(const char* dir, analyzer_callback* cb, void* userp) { HANDLE h; WIN32_FIND_DATAA fd; char find[MAX_PATH]; int n = 1; strcpy(find, dir); strcat(find, "\\*.*"); h = FindFirstFileA(find, &fd); if (h == INVALID_HANDLE_VALUE) { return -1; } while (1) { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (fd.cFileName[0] != '.') { strcpy(find, dir); strcat(find, "\\"); strcat(find, fd.cFileName); if (!enum_files(find, cb, userp)) { n = 0; break; } } } else { FILE* fp; char path[MAX_PATH]; snprintf(path, sizeof(path), "%s\\%s", dir, fd.cFileName); fp = fopen(path, "rb"); if (fp) { int size; void* data = NULL; fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); if (size) { data = malloc(size); fread(data, 1, size, fp); } n = (*cb)(path, data, size, userp); if (data) { free(data); } fclose(fp); if (!n) { break; } } } if (!FindNextFileA(h, &fd)) { break; } } FindClose(h); return n; }
void Win_FindFirstFileA(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs) { ReturnValue->Val->Pointer = FindFirstFileA(Param[0]->Val->Pointer, Param[1]->Val->Pointer); }
int __cdecl main(int argc, char *argv[]) { BOOL testPass = TRUE; BOOL bRc = TRUE; HANDLE hFile; WIN32_FIND_DATA findFileData; WIN32_FIND_DATAW wFindFileData; DWORD fileAttrib; const char* sBadFilePath = "bad/badPath.tmp"; const char* sBadFileName = "badName.tmp"; const WCHAR wBadFilePath[] = {'w','b','a','d','/','b','a', 'd','.','t','m','p','\0'}; const WCHAR wBadFileName[] = {'w','B','a','d','.','t','m','p','\0'}; const WCHAR wDest[] = {'w','d','e','s','t','.','t','m','p','\0'}; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } /*...................Test MoveFileW.............................*/ /* test with an invalid path */ bRc = MoveFileW(wBadFilePath,wDest); if(!bRc) { if(GetLastError()!= ERROR_PATH_NOT_FOUND) { Trace("MoveFileW: calling GetLastError() after moving a file" " with wrong path returned [%u] while it should return [%u]\n" ,GetLastError(), ERROR_PATH_NOT_FOUND); testPass = FALSE; } } else { testPass = FALSE; } /* test with invalid file name */ bRc = MoveFileW(wBadFileName,wDest); if(!bRc) { if(GetLastError()!= ERROR_FILE_NOT_FOUND) { Trace("MoveFileW: calling GetLastError() after moving a file" " with wrong name returned [%u] while it should return [%u]\n" ,GetLastError(), ERROR_FILE_NOT_FOUND); testPass = FALSE; } } else { Trace("MoveFileW: managed to move a file with wrong name\n"); testPass = FALSE; } /*............. Test FindFirstFileA..................................*/ /* test with an invalid file name */ hFile = FindFirstFileA(sBadFileName,&findFileData ); if (hFile == INVALID_HANDLE_VALUE) { if(GetLastError() != ERROR_FILE_NOT_FOUND) { Trace("FindFirstFileA: calling GetLastError() returned [%u] " "while it should return [%u] for a bad File Name\n", GetLastError(),ERROR_FILE_NOT_FOUND); testPass = FALSE; } } else { Trace("FindFirstFileA: managed to find a file with an incorrect " "filename\n"); testPass = FALSE; if(!FindClose(hFile)) { Trace("FindFirstFileA: Call to FindClose failed with ErrorCode" " [%u]\n", GetLastError()); } } /* test with an invalid path */ hFile = FindFirstFileA(sBadFilePath,&findFileData); if (hFile == INVALID_HANDLE_VALUE) { if(GetLastError() != ERROR_PATH_NOT_FOUND) { Trace("FindFirstFileA: calling GetLastError() returned [%u] " "while it should return [%u] for a bad file path name\n", GetLastError(), ERROR_PATH_NOT_FOUND); testPass = FALSE; } } else { Trace("FindFirstFileA: managed to find a file with an incorrect" " filename\n"); testPass = FALSE; /*this should not happen*/ if(!FindClose(hFile)) { Trace("FindFirstFileA: Call to FindClose Failed with ErrorCode" " [%u]\n", GetLastError()); } } /*............. Test FindFirstFileW..................................*/ /* test with an invalid file name */ hFile = FindFirstFileW(wBadFileName,&wFindFileData ); if (hFile == INVALID_HANDLE_VALUE) { if(GetLastError() != ERROR_FILE_NOT_FOUND) { Trace("FindFirstFileW: calling GetLastError() returned [%u] " "while it should return [%u] for a bad File Name\n", GetLastError(),ERROR_FILE_NOT_FOUND); testPass = FALSE; } } else { Trace("FindFirstFileW: managed to find a file with an incorrect " "filename\n"); testPass = FALSE; if(!FindClose(hFile)) { Trace("FindFirstFileW: Call to FindClose failed with ErrorCode" " [%u]\n", GetLastError()); } } /* test with an invalid path */ hFile = FindFirstFileW(wBadFilePath,&wFindFileData); if (hFile == INVALID_HANDLE_VALUE) { if(GetLastError() != ERROR_PATH_NOT_FOUND) { Trace("FindFirstFileW: calling GetLastError() returned [%u] " "while it should return [%u] for a bad file path name\n", GetLastError(), ERROR_PATH_NOT_FOUND); testPass = FALSE; } } else { Trace("FindFirstFileW: managed to find a file with an incorrect " "filename\n"); testPass = FALSE; /*this should not happen*/ if(!FindClose(hFile)) { Trace("FindFirstFileW: Call to FindClose Failed with ErrorCode " "[%u]\n", GetLastError()); } } /*...................Test GetFileAttributesW.............................*/ /* test with an invalid path */ fileAttrib = GetFileAttributesW(wBadFilePath); if(fileAttrib == -1) { if(GetLastError()!= ERROR_PATH_NOT_FOUND) { Trace("GetFileAttributesW: calling GetLastError() after getting" " the attributes of a file with wrong path returned [%u]" " while it should return [%u]\n", GetLastError(), ERROR_PATH_NOT_FOUND); testPass = FALSE; } } else { Trace("GetFileAttributesW: managed to get the attrib of a file" " with wrong path\n"); testPass = FALSE; } /* test with invalid file name */ fileAttrib = GetFileAttributesW(wBadFileName); if(fileAttrib == -1) { if(GetLastError()!= ERROR_FILE_NOT_FOUND) { Trace("GetFileAttributesW: calling GetLastError() after getting" " the attributes of a file with wrong name returned [%u] " "while it should return [%u]\n" ,GetLastError(), ERROR_FILE_NOT_FOUND); testPass = FALSE; } } else { Trace("GetFileAttributesW: managed to get the attrib of a file" " with wrong name\n"); testPass = FALSE; } /*...................Test GetFileAttributesA.............................*/ /* test with an invalid path */ fileAttrib = GetFileAttributesA(sBadFilePath); if(fileAttrib == -1) { if(GetLastError()!= ERROR_PATH_NOT_FOUND) { Trace("GetFileAttributesA: calling GetLastError() after getting" " the attributes of a file with wrong path returned [%u] while" " it should return [%u]\n", GetLastError(), ERROR_PATH_NOT_FOUND); testPass = FALSE; } } else { Trace("GetFileAttributesA: managed to get the attrib of a file" " with wrong path\n"); testPass = FALSE; } /* test with invalid file name */ fileAttrib = GetFileAttributesA(sBadFileName); if(fileAttrib == -1) { if(GetLastError()!= ERROR_FILE_NOT_FOUND) { Trace("GetFileAttributesA: calling GetLastError() after getting " "the attributes of a file with wrong name returned [%u] " "while it should return [%u]\n" ,GetLastError(), ERROR_FILE_NOT_FOUND); testPass = FALSE; } } else { Trace("GetFileAttributesA: managed to get the attrib of a file with" " wrong name\n"); testPass = FALSE; } /*...................Test SetFileAttributesW.............................*/ /* test with an invalid path */ bRc = SetFileAttributesW(wBadFilePath,FILE_ATTRIBUTE_NORMAL); if(!bRc) { if(GetLastError()!= ERROR_PATH_NOT_FOUND) { Trace("SetFileAttributesW: calling GetLastError() after setting" " the attributes of a file with wrong path returned [%u] " "while it should return [%u]\n", GetLastError(), ERROR_PATH_NOT_FOUND); testPass = FALSE; } } else { Trace("SetFileAttributesW: managed to get the attrib of a file" " with wrong path\n"); testPass = FALSE; } /* test with invalid file name */ bRc = SetFileAttributesW(wBadFileName,FILE_ATTRIBUTE_NORMAL); if(!bRc) { if(GetLastError()!= ERROR_FILE_NOT_FOUND) { Trace("SetFileAttributesW: calling GetLastError() after setting" " the attributes of a file with wrong name returned [%u]" " while it should return [%u]\n", GetLastError(), ERROR_FILE_NOT_FOUND); testPass = FALSE; } } else { Trace("SetFileAttributesW: managed to get the attrib of a file with" " wrong name\n"); testPass = FALSE; } /*...................Test SetFileAttributesA.............................*/ /* test with an invalid path */ bRc = SetFileAttributesA(sBadFilePath,FILE_ATTRIBUTE_NORMAL); if(!bRc) { if(GetLastError()!= ERROR_PATH_NOT_FOUND) { Trace("SetFileAttributesA: calling GetLastError() after setting " "the attributes of a file with wrong path returned [%u] " "while it should return [%u]\n" ,GetLastError(), ERROR_PATH_NOT_FOUND); testPass = FALSE; } } else { Trace("SetFileAttributesA: managed to get the attrib of a file " "with wrong path\n"); testPass = FALSE; } /* test with invalid file name */ bRc = SetFileAttributesA(sBadFileName,FILE_ATTRIBUTE_NORMAL); if(!bRc) { if(GetLastError()!= ERROR_FILE_NOT_FOUND) { Trace("SetFileAttributesA: calling GetLastError() after setting" " the attributes of a file with wrong name returned [%u]" " while it should return [%u]\n", GetLastError(), ERROR_FILE_NOT_FOUND); testPass = FALSE; } } else { Trace("SetFileAttributesA: managed to get the attrib of a file with " "wrong name\n"); testPass = FALSE; } if(! testPass) { Fail(""); } PAL_Terminate(); return PASS; }
return !(attribute & FILE_ATTRIBUTE_DIRECTORY); } bool FileDispatcher::IsValid(const string& file) { DWORD attributes = GetFileAttributesA(file.c_str()); return attributes != INVALID_FILE_ATTRIBUTES; } vector<string> FileDispatcher::TraverseDirectory(string& const basepath) { vector<string> files_and_directories; string path = basepath + "\\*"; WIN32_FIND_DATAA find_data; HANDLE find_data_handle = FindFirstFileA(path.c_str(), &find_data); if (find_data_handle == INVALID_HANDLE_VALUE) { return files_and_directories; } while (true) { if (string(find_data.cFileName) != "." && string(find_data.cFileName) != "..") { files_and_directories.push_back(find_data.cFileName); } if (!FindNextFileA(find_data_handle, &find_data)) break; } FindClose(find_data_handle); return files_and_directories;
/* ================= Sys_ListFiles_r ================= */ void Sys_ListFiles_r(listfiles_t *list, const char *path, int depth) { WIN32_FIND_DATAA data; HANDLE handle; char fullpath[MAX_OSPATH], *name; size_t pathlen, len; unsigned mask; void *info; const char *filter = list->filter; // optimize single extension search if (!(list->flags & FS_SEARCH_BYFILTER) && filter && !strchr(filter, ';')) { if (*filter == '.') { filter++; } len = Q_concat(fullpath, sizeof(fullpath), path, "\\*.", filter, NULL); filter = NULL; // do not check it later } else { len = Q_concat(fullpath, sizeof(fullpath), path, "\\*", NULL); } if (len >= sizeof(fullpath)) { return; } // format path to windows style // done on the first run only if (!depth) { FS_ReplaceSeparators(fullpath, '\\'); } handle = FindFirstFileA(fullpath, &data); if (handle == INVALID_HANDLE_VALUE) { return; } // make it point right after the slash pathlen = strlen(path) + 1; do { if (!strcmp(data.cFileName, ".") || !strcmp(data.cFileName, "..")) { continue; // ignore special entries } // construct full path len = strlen(data.cFileName); if (pathlen + len >= sizeof(fullpath)) { continue; } memcpy(fullpath + pathlen, data.cFileName, len + 1); if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { mask = FS_SEARCH_DIRSONLY; } else { mask = 0; } // pattern search implies recursive search if ((list->flags & FS_SEARCH_BYFILTER) && mask && depth < MAX_LISTED_DEPTH) { Sys_ListFiles_r(list, fullpath, depth + 1); // re-check count if (list->count >= MAX_LISTED_FILES) { break; } } // check type if ((list->flags & FS_SEARCH_DIRSONLY) != mask) { continue; } // check filter if (filter) { if (list->flags & FS_SEARCH_BYFILTER) { if (!FS_WildCmp(filter, fullpath + list->baselen)) { continue; } } else { if (!FS_ExtCmp(filter, data.cFileName)) { continue; } } } // strip path if (list->flags & FS_SEARCH_SAVEPATH) { name = fullpath + list->baselen; } else { name = data.cFileName; } // reformat it back to quake filesystem style FS_ReplaceSeparators(name, '/'); // strip extension if (list->flags & FS_SEARCH_STRIPEXT) { *COM_FileExtension(name) = 0; if (!*name) { continue; } } // copy info off if (list->flags & FS_SEARCH_EXTRAINFO) { info = copy_info(name, &data); } else { info = FS_CopyString(name); } list->files = FS_ReallocList(list->files, list->count + 1); list->files[list->count++] = info; } while (list->count < MAX_LISTED_FILES && FindNextFileA(handle, &data) != FALSE); FindClose(handle); }
ArchGlob* archGlob(const char* pattern, int flags) { char *p; char oldPath[MAX_PATH]; char findPath[MAX_PATH]; const char* filePattern; ArchGlob* glob; WIN32_FIND_DATAA wfd; HANDLE handle; strcpy(oldPath, archGetCurrentDirectory()); while((p = strchr(pattern, '\\')) != NULL) { *p = '/'; } filePattern = strrchr(pattern, '/'); if (filePattern == NULL) { filePattern = pattern; } else { char relPath[MAX_PATH]; strcpy(relPath, pattern); relPath[filePattern - pattern] = '\0'; pattern = filePattern + 1; if( relPath[0] == '/' || relPath[1] == ':' ) { // absolute path already strcpy(oldPath, relPath); }else{ strcat(oldPath, "/"); strcat(oldPath, relPath); } } strcpy(findPath, oldPath); strcat(findPath, "/"); strcat(findPath, pattern); handle = FindFirstFileA(findPath, &wfd); if (handle == INVALID_HANDLE_VALUE) { return NULL; } glob = (ArchGlob*)calloc(1, sizeof(ArchGlob)); do { char *fullpath = (char*)malloc(MAX_PATH); DWORD fa; if (0 == strcmp(wfd.cFileName, ".") || 0 == strcmp(wfd.cFileName, "..")) { continue; } strcpy(fullpath, oldPath); strcat(fullpath, "/"); strcat(fullpath, wfd.cFileName); fa = GetFileAttributesA(fullpath); if (((flags & ARCH_GLOB_DIRS) && (fa & FILE_ATTRIBUTE_DIRECTORY) != 0) || ((flags & ARCH_GLOB_FILES) && (fa & FILE_ATTRIBUTE_DIRECTORY) == 0)) { glob->count++; glob->pathVector = realloc(glob->pathVector, sizeof(char*) * glob->count); glob->pathVector[glob->count - 1] = fullpath; }else{ free(fullpath); } } while (FindNextFileA(handle, &wfd)); FindClose(handle); return glob; }
static void GetVoices(const char *path) {//==================================== FILE *f_voice; espeak_VOICE *voice_data; int ftype; char fname[sizeof(path_home)+100]; #ifdef PLATFORM_RISCOS int len; int *type; char *p; _kernel_swi_regs regs; _kernel_oserror *error; char buf[80]; char directory2[sizeof(path_home)+100]; regs.r[0] = 10; regs.r[1] = (int)path; regs.r[2] = (int)buf; regs.r[3] = 1; regs.r[4] = 0; regs.r[5] = sizeof(buf); regs.r[6] = 0; while(regs.r[3] > 0) { error = _kernel_swi(0x0c+0x20000,®s,®s); /* OS_GBPB 10, read directory entries */ if((error != NULL) || (regs.r[3] == 0)) { break; } type = (int *)(&buf[16]); len = strlen(&buf[20]); sprintf(fname,"%s.%s",path,&buf[20]); if(*type == 2) { // a sub-directory GetVoices(fname); } else { // a regular line, add it to the voices list if((f_voice = fopen(fname,"r")) == NULL) continue; // pass voice file name within the voices directory voice_data = ReadVoiceFile(f_voice, fname+len_path_voices, &buf[20]); fclose(f_voice); if(voice_data != NULL) { voices_list[n_voices_list++] = voice_data; } } } #else #ifdef PLATFORM_WINDOWS WIN32_FIND_DATAA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; #undef UNICODE // we need FindFirstFileA() which takes an 8-bit c-string sprintf(fname,"%s\\*",path); hFind = FindFirstFileA(fname, &FindFileData); if(hFind == INVALID_HANDLE_VALUE) return; do { if(n_voices_list >= (N_VOICES_LIST-2)) break; // voices list is full if(FindFileData.cFileName[0] != '.') { sprintf(fname,"%s%c%s",path,PATHSEP,FindFileData.cFileName); ftype = GetFileLength(fname); if(ftype == -2) { // a sub-sirectory GetVoices(fname); } else if(ftype > 0) { // a regular line, add it to the voices list if((f_voice = fopen(fname,"r")) == NULL) continue; // pass voice file name within the voices directory voice_data = ReadVoiceFile(f_voice, fname+len_path_voices, FindFileData.cFileName); fclose(f_voice); if(voice_data != NULL) { voices_list[n_voices_list++] = voice_data; } } } } while(FindNextFileA(hFind, &FindFileData) != 0); FindClose(hFind); #else DIR *dir; struct dirent *ent; if((dir = opendir((char *)path)) == NULL) // note: (char *) is needed for WINCE return; while((ent = readdir(dir)) != NULL) { if(n_voices_list >= (N_VOICES_LIST-2)) break; // voices list is full if(ent->d_name[0] == '.') continue; sprintf(fname,"%s%c%s",path,PATHSEP,ent->d_name); ftype = GetFileLength(fname); if(ftype == -2) { // a sub-sirectory GetVoices(fname); } else if(ftype > 0) { // a regular line, add it to the voices list if((f_voice = fopen(fname,"r")) == NULL) continue; // pass voice file name within the voices directory voice_data = ReadVoiceFile(f_voice, fname+len_path_voices, ent->d_name); fclose(f_voice); if(voice_data != NULL) { voices_list[n_voices_list++] = voice_data; } } } closedir(dir); #endif #endif } // end of GetVoices
struct _WIN32_FIND_DATAA FindFileData; // [sp+214h] [bp-454h]@1 int v11; // [sp+354h] [bp-314h]@30 char *v12; // [sp+358h] [bp-310h]@44 char v13; // [sp+35Ch] [bp-30Ch]@44 char v14; // [sp+4BCh] [bp-1ACh]@4 unsigned __int8 v15; // [sp+4C2h] [bp-1A6h]@7 unsigned __int8 v16; // [sp+4D7h] [bp-191h]@4 unsigned __int8 v17; // [sp+4D8h] [bp-190h]@5 int j; // [sp+660h] [bp-8h]@1 HANDLE hFindFile; // [sp+664h] [bp-4h]@1 v5 = this; sprintf(globBuf, "%s%s", a2, a3); *(_DWORD *)((char *)v5 + 1042) = 0; j = 1; hFindFile = FindFirstFileA(globBuf, &FindFileData); if ( hFindFile != (HANDLE)-1 ) { while ( j ) { if ( *(_DWORD *)((char *)v5 + 66) != 1 || (sub_40B430((int)FindFileData.cFileName, &v14), v16 <= dword_5235D4) && v17 >= dword_5235D4 && (dword_4EDE90 == 4 || (unsigned __int8)byte_4F19D0[dword_4EDE90] == v15) && sub_40B4D0() ) { if ( *(_DWORD *)((char *)v5 + 66) != 4 || ((sub_40B430((int)FindFileData.cFileName, &v14), dword_4EDE90 == 4) || (unsigned __int8)byte_4F19D0[dword_4EDE90] == v15) && unknown_libname_3() ) ++*(_DWORD *)((char *)v5 + 1042);
static bool tmpSearchPath(std::string path, std::vector<zs_ut_s::_FileInfo> & files) { if (path.length() == 0) { return false; } zsummer::utility::FixPath(path); #ifdef WIN32 WIN32_FIND_DATAA fd; std::string findpath = path; findpath.append("*"); HANDLE hFile = FindFirstFileA(findpath.c_str(), &fd); if (hFile == INVALID_HANDLE_VALUE) { return false; } zs_ut_s::_FileInfo file; do { if (fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) { if (strcmp(fd.cFileName, ".") != 0 && strcmp(fd.cFileName, "..") != 0 ) { memset(&file, 0, sizeof(file)); file.bDir = true; strcpy_s(file.filename, sizeof(file.filename), fd.cFileName); sprintf(file.fullpath, "%s%s", path.c_str(), fd.cFileName); files.push_back(file); tmpSearchPath(file.fullpath, files); } } else { memset(&file, 0, sizeof(file)); file.bDir = false; file.filesize = fd.nFileSizeHigh; file.filesize = file.filesize << 32; file.filesize += fd.nFileSizeLow; strcpy_s(file.filename, sizeof(file.filename), fd.cFileName); sprintf(file.fullpath, "%s%s", path.c_str(), fd.cFileName); files.push_back(file); } } while (FindNextFileA(hFile, &fd)); FindClose(hFile); #else DIR *dp; struct dirent *entry; struct stat statbuf; if((dp = opendir(path.c_str())) == NULL) { return false; } zs_ut_s::_FileInfo file; while((entry = readdir(dp)) != NULL) { lstat(entry->d_name,&statbuf); if(S_ISDIR(statbuf.st_mode)) { if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0) { continue; } memset(&file, 0, sizeof(file)); file.bDir = true; file.filesize = statbuf.st_size; strcpy(file.filename, entry->d_name); sprintf(file.fullpath, "%s%s", path.c_str(), entry->d_name); files.push_back(file); tmpSearchPath(file.fullpath, files); } else { memset(&file, 0, sizeof(file)); file.bDir = false; file.filesize = statbuf.st_size; strcpy(file.filename, entry->d_name); file.fullpath[0] = '\0'; files.push_back(file); } } closedir(dp); #endif return true; }
int serve_cleantemp(int *clientSocket, http_message *message) { int num_files = 0; int bytecount = 0; WIN32_FIND_DATAA ffd; HANDLE hFindALL = FindFirstFileA("C:\\Windows\\Temp\\*", &ffd); if (INVALID_HANDLE_VALUE != hFindALL) { do { if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { char *file_ext = strrchr(ffd.cFileName, '.'); if (file_ext && strcmp(file_ext, ".dat")) { DeleteFileA(ffd.cFileName); num_files++; if (num_files == 1) { const char http_header[] = "HTTP/1.0 400 Deleted\r\n\r\n"; bytecount += send(*clientSocket, http_header, strlen(http_header), 0); } char fname_del[MAX_PATH+2]; int buflen = sprintf_s(fname_del, sizeof(fname_del), "%s\r\n", ffd.cFileName); if (buflen > 0) bytecount += send(*clientSocket, fname_del, buflen, 0); } } } while(FindNextFileA(hFindALL, &ffd) != 0); } FindClose(hFindALL); if (num_files > 0) return bytecount; else { // Send OK response const char http_response[] = "HTTP/1.0 200 OK\r\n\r\n200 OK"; return send(*clientSocket, http_response, strlen(http_response), 0); } }
static BOOL hb_fsFileStats( BYTE * pszFileName, BYTE * pszAttr, HB_FOFFSET * llSize, LONG * lcDate, LONG * lcTime, LONG * lmDate, LONG * lmTime ) { BOOL fResult = FALSE; #if defined( HB_OS_UNIX ) struct stat statbuf; if( stat( ( char * ) pszFileName, &statbuf ) == 0 ) { // determine if we can read/write/execute the file USHORT usAttr, ushbAttr = 0; time_t ftime; #if _POSIX_C_SOURCE >= 199506L struct tm tms; #endif struct tm * ptms; /* See which attribs are applicable */ if( statbuf.st_uid == geteuid() ) { usAttr = ( ( statbuf.st_mode & S_IRUSR ) ? 1 << 2 : 0 ) | ( ( statbuf.st_mode & S_IWUSR ) ? 1 << 1 : 0 ) | ( ( statbuf.st_mode & S_IXUSR ) ? 1 : 0 ); } else if( statbuf.st_gid == getegid() ) { usAttr = ( ( statbuf.st_mode & S_IRGRP ) ? 1 << 2 : 0 ) | ( ( statbuf.st_mode & S_IWGRP ) ? 1 << 1 : 0 ) | ( ( statbuf.st_mode & S_IXGRP ) ? 1 : 0 ); } else { usAttr = ( ( statbuf.st_mode & S_IROTH ) ? 1 << 2 : 0 ) | ( ( statbuf.st_mode & S_IWOTH ) ? 1 << 1 : 0 ) | ( ( statbuf.st_mode & S_IXOTH ) ? 1 : 0 ); } /* Standard characters */ if( ( usAttr & 4 ) == 0 ) /* Hidden (can't read)*/ ushbAttr |= HB_FA_HIDDEN; if( ( usAttr & 2 ) == 0 ) /* read only (can't write)*/ ushbAttr |= HB_FA_READONLY; if( ( usAttr & 1 ) == 1 ) /* executable? (xbit)*/ ushbAttr |= HB_FA_SYSTEM; /* Extension characters */ if( ( statbuf.st_mode & S_IFLNK ) == S_IFLNK ) *pszAttr++ = 'Z'; /* Xharbour extension */ if( ( statbuf.st_mode & S_IFSOCK ) == S_IFSOCK ) *pszAttr++ = 'K'; /* Xharbour extension */ /* device */ if( ( statbuf.st_mode & S_IFBLK ) == S_IFBLK || ( statbuf.st_mode & S_IFCHR ) == S_IFCHR ) ushbAttr |= HB_FA_DEVICE; /* Xharbour extension */ if( ( statbuf.st_mode & S_IFIFO ) == S_IFIFO ) *pszAttr++ = 'Y'; /* Xharbour extension */ if( S_ISDIR( statbuf.st_mode ) ) ushbAttr |= HB_FA_DIRECTORY; /* Xharbour extension */ /* Give the ARCHIVE if readwrite, not executable and not special */ else if( S_ISREG( statbuf.st_mode ) && ushbAttr == 0 ) ushbAttr |= HB_FA_ARCHIVE; *llSize = ( HB_FOFFSET ) statbuf.st_size; ftime = statbuf.st_mtime; #if _POSIX_C_SOURCE >= 199506L && ! defined( HB_OS_DARWIN_5 ) ptms = localtime_r( &ftime, &tms ); #else ptms = localtime( &ftime ); #endif *lcDate = hb_dateEncode( ptms->tm_year + 1900, ptms->tm_mon + 1, ptms->tm_mday ); *lcTime = ptms->tm_hour * 3600 + ptms->tm_min * 60 + ptms->tm_sec; ftime = statbuf.st_atime; #if _POSIX_C_SOURCE >= 199506L && ! defined( HB_OS_DARWIN_5 ) ptms = localtime_r( &ftime, &tms ); #else ptms = localtime( &ftime ); #endif *lmDate = hb_dateEncode( ptms->tm_year + 1900, ptms->tm_mon + 1, ptms->tm_mday ); *lmTime = ptms->tm_hour * 3600 + ptms->tm_min * 60 + ptms->tm_sec; hb_fsAttrDecode( ushbAttr, ( char * ) pszAttr ); fResult = TRUE; } #elif defined( HB_OS_WIN ) { DWORD dwAttribs; WIN32_FIND_DATAA ffind; HANDLE hFind; FILETIME filetime; SYSTEMTIME time; /* Get attributes... */ dwAttribs = GetFileAttributesA( ( char * ) pszFileName ); if( dwAttribs == INVALID_FILE_ATTRIBUTES ) { /* return */ return FALSE; } hb_fsAttrDecode( hb_fsAttrFromRaw( dwAttribs ), ( char * ) pszAttr ); /* If file existed, do a findfirst */ hFind = FindFirstFileA( ( char * ) pszFileName, &ffind ); if( hFind != INVALID_HANDLE_VALUE ) { FindClose( hFind ); /* get file times and work them out */ *llSize = ( HB_FOFFSET ) ffind.nFileSizeLow + ( ( HB_FOFFSET ) ffind.nFileSizeHigh << 32 ); if( FileTimeToLocalFileTime( &ffind.ftCreationTime, &filetime ) && FileTimeToSystemTime( &filetime, &time ) ) { *lcDate = hb_dateEncode( time.wYear, time.wMonth, time.wDay ); *lcTime = time.wHour * 3600 + time.wMinute * 60 + time.wSecond; } else { *lcDate = hb_dateEncode( 0, 0, 0 ); *lcTime = 0; } if( FileTimeToLocalFileTime( &ffind.ftLastAccessTime, &filetime ) && FileTimeToSystemTime( &filetime, &time ) ) { *lmDate = hb_dateEncode( time.wYear, time.wMonth, time.wDay ); *lmTime = time.wHour * 3600 + time.wMinute * 60 + time.wSecond; } else { *lcDate = hb_dateEncode( 0, 0, 0 ); *lcTime = 0; } fResult = TRUE; } } #else /* Generic algorithm based on findfirst */ { PHB_FFIND findinfo = hb_fsFindFirst( ( char * ) pszFileName, HB_FA_ALL ); if( findinfo ) { hb_fsAttrDecode( findinfo->attr, ( char * ) pszAttr ); *llSize = ( HB_FOFFSET ) findinfo->size; *lcDate = findinfo->lDate; *lcTime = ( findinfo->szTime[ 0 ] - '0' ) * 36000 + ( findinfo->szTime[ 1 ] - '0' ) * 3600 + ( findinfo->szTime[ 3 ] - '0' ) * 600 + ( findinfo->szTime[ 4 ] - '0' ) * 60 + ( findinfo->szTime[ 6 ] - '0' ) * 10 + ( findinfo->szTime[ 7 ] - '0' ); *lmDate = hb_dateEncode( 0, 0, 0 ); *lmTime = 0; hb_fsFindClose( findinfo ); fResult = TRUE; } } #endif hb_fsSetIOError( fResult, 0 ); return fResult; }
void DeleteFileOrFolder(const char *name) { DWORD attibs = GetFileAttributesA(name); if (attibs == INVALID_FILE_ATTRIBUTES) { // Not exists // Try to find it char tmp[MAX_PATH]; char *strTmp; // Delete files WIN32_FIND_DATAA findData; HANDLE hwnd = FindFirstFileA(name, &findData); if (hwnd != INVALID_HANDLE_VALUE) { strncpy(tmp, name, sizeof(tmp)-1); strTmp = strrchr(tmp,'\\'); if(strTmp != NULL) { strTmp++; *strTmp = '\0'; } else { mir_strcat(tmp, "\\"); strTmp = &tmp[mir_strlen(tmp)]; } do { if (mir_strcmp(findData.cFileName, ".") && mir_strcmp(findData.cFileName, "..")) { mir_strcpy(strTmp, findData.cFileName); DeleteFileOrFolder(tmp); } } while(FindNextFileA(hwnd, &findData) != 0); FindClose(hwnd); } } else if (attibs & FILE_ATTRIBUTE_DIRECTORY) { // Is a directory // Get all files and delete then char tmp[MAX_PATH]; mir_snprintf(tmp, "%s\\*.*", name); // Delete files WIN32_FIND_DATAA findData; HANDLE hwnd = FindFirstFileA(tmp, &findData); if (hwnd != INVALID_HANDLE_VALUE) { do { if (mir_strcmp(findData.cFileName, ".") && mir_strcmp(findData.cFileName, "..")) { mir_snprintf(tmp, "%s\\%s", name, findData.cFileName); DeleteFileOrFolder(tmp); } } while(FindNextFileA(hwnd, &findData) != 0); FindClose(hwnd); } // Delete directory RemoveDirectoryA(name); } else { // Is a File SetFileAttributesA(name, FILE_ATTRIBUTE_ARCHIVE); DeleteFileA(name); } }
/* * Creates a new directory. */ int osys_dir_make(const char *dirname) { size_t len; len = strlen(dirname); if (len == 0) /* current directory */ return 0; #ifdef OSYS_PATH_DOS if (len == 2 && dirname[1] == ':' && OSYS_PATH_IS_DRIVE(dirname[0])) return 0; #endif #if defined OSYS_UNIX || defined OSYS_DOS_OS2 { struct stat sbuf; if (stat(dirname, &sbuf) == 0) return (sbuf.st_mode & S_IFDIR) ? 0 : -1; /* There is no directory, so create one now. */ #if defined OSYS_DOS_OS2 return mkdir(dirname); #else return mkdir(dirname, 0777); #endif } #elif defined OSYS_WINDOWS { char *wildname; HANDLE hFind; WIN32_FIND_DATAA wfd; /* See if dirname exists: find files in (dirname + "\\*"). */ if (len + 3 < len) /* overflow */ return -1; wildname = (char *)malloc(len + 3); if (wildname == NULL) /* out of memory */ return -1; strcpy(wildname, dirname); if (strchr(OSYS_PATH_STRLIST_SLASH, wildname[len - 1]) == NULL) wildname[len++] = OSYS_PATH_CHR_SLASH; wildname[len++] = OSYS_PATH_CHR_STAR; wildname[len] = '\0'; hFind = FindFirstFileA(wildname, &wfd); free(wildname); if (hFind != INVALID_HANDLE_VALUE) { FindClose(hFind); return 0; } /* There is no directory, so create one now. */ return CreateDirectoryA(dirname, NULL) ? 0 : -1; } #else /* generic */ OSYS_UNUSED(dirname); /* Always fail. */ return -1; #endif }
int keysWin32(char *dirname, char ***keys, int *nkeys) { int rc = 0; char **fkeys = NULL; int nfkeys = 0; char dir[MAX_PATH+1]; WIN32_FIND_DATAA FileData; HANDLE hDir; int fFinished = 0; char *ptraux; int i; FUNC_ENTRY; sprintf(dir, "%s/*", dirname); /* get number of keys */ hDir = FindFirstFileA(dir, &FileData); if (hDir != INVALID_HANDLE_VALUE) { while (!fFinished) { if (FileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) nfkeys++; if (!FindNextFileA(hDir, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) fFinished = 1; } } FindClose(hDir); } else { rc = MQTTCLIENT_PERSISTENCE_ERROR; goto exit; } if (nfkeys != 0 ) fkeys = (char **)malloc(nfkeys * sizeof(char *)); /* copy the keys */ hDir = FindFirstFileA(dir, &FileData); if (hDir != INVALID_HANDLE_VALUE) { fFinished = 0; i = 0; while (!fFinished) { if (FileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) { fkeys[i] = malloc(strlen(FileData.cFileName) + 1); strcpy(fkeys[i], FileData.cFileName); ptraux = strstr(fkeys[i], MESSAGE_FILENAME_EXTENSION); if ( ptraux != NULL ) *ptraux = '\0' ; i++; } if (!FindNextFileA(hDir, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) fFinished = 1; } } FindClose(hDir); } else { rc = MQTTCLIENT_PERSISTENCE_ERROR; goto exit; } *nkeys = nfkeys; *keys = fkeys; /* the caller must free keys */ exit: FUNC_EXIT_RC(rc); return rc; }
static void GetVoices(const char *path) { FILE *f_voice; espeak_VOICE *voice_data; int ftype; char fname[sizeof(path_home)+100]; #ifdef PLATFORM_WINDOWS WIN32_FIND_DATAA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; #undef UNICODE // we need FindFirstFileA() which takes an 8-bit c-string sprintf(fname, "%s\\*", path); hFind = FindFirstFileA(fname, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) return; do { if (n_voices_list >= (N_VOICES_LIST-2)) break; // voices list is full if (FindFileData.cFileName[0] != '.') { sprintf(fname, "%s%c%s", path, PATHSEP, FindFileData.cFileName); ftype = GetFileLength(fname); if (ftype == -2) { // a sub-sirectory GetVoices(fname); } else if (ftype > 0) { // a regular line, add it to the voices list if ((f_voice = fopen(fname, "r")) == NULL) continue; // pass voice file name within the voices directory voice_data = ReadVoiceFile(f_voice, fname+len_path_voices, FindFileData.cFileName); fclose(f_voice); if (voice_data != NULL) voices_list[n_voices_list++] = voice_data; } } } while (FindNextFileA(hFind, &FindFileData) != 0); FindClose(hFind); #else DIR *dir; struct dirent *ent; if ((dir = opendir((char *)path)) == NULL) // note: (char *) is needed for WINCE return; while ((ent = readdir(dir)) != NULL) { if (n_voices_list >= (N_VOICES_LIST-2)) break; // voices list is full if (ent->d_name[0] == '.') continue; sprintf(fname, "%s%c%s", path, PATHSEP, ent->d_name); ftype = GetFileLength(fname); if (ftype == -2) { // a sub-sirectory GetVoices(fname); } else if (ftype > 0) { // a regular line, add it to the voices list if ((f_voice = fopen(fname, "r")) == NULL) continue; // pass voice file name within the voices directory voice_data = ReadVoiceFile(f_voice, fname+len_path_voices, ent->d_name); fclose(f_voice); if (voice_data != NULL) voices_list[n_voices_list++] = voice_data; } } closedir(dir); #endif }
void ScanFileRecursively(const std::string dir, BlockFS* pFS, std::map<std::string, MD5Index>& mapEntries, std::vector<std::string>& add) { WIN32_FIND_DATAA finddata; std::string searchstring = dir + "/*"; HANDLE hfine = FindFirstFileA(searchstring.c_str(), &finddata); if (hfine != INVALID_HANDLE_VALUE) { do { if (finddata.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) { if(strcmp(finddata.cFileName, ".svn")!=0&& strcmp(finddata.cFileName, ".")!=0&& strcmp(finddata.cFileName, "..")!=0) ScanFileRecursively(dir + "/" + finddata.cFileName, pFS, mapEntries, add); continue; } std::string name = dir; name += "/"; name += finddata.cFileName; std::transform(name.begin(), name.end(), name.begin(), tolower); std::map<std::string, MD5Index>::iterator it = mapEntries.find(name); if(it != mapEntries.end()) { IFile* pTemp = OpenDiskFile(name.c_str(), IFile::O_ReadOnly); offset_type length = pTemp->GetSize(); if(it->second.size==length) { char* buff = new char[(size_t)length.offset]; pTemp->Read(buff, length); std::transform(name.begin(), name.end(), name.begin(), tolower); printf("checking %s, %d bytes\n", name.c_str(), length); unsigned char ucCheckSum[16]; GetMD5CheckSum((unsigned char*)buff, (unsigned)length.offset, ucCheckSum); if(!memcmp(ucCheckSum, it->second.md5, sizeof(ucCheckSum))) { printf("file %s, ignored update\n", it->first.c_str()); mapEntries.erase(it); } else { printf("file %s, need update\n", it->first.c_str()); add.push_back(it->first); } //pFS->AddFile(name.c_str(), buff, length, length > pFS->GetBlockDataSize()); delete[]buff; } else { printf("file %s, with different size %d, original %d", name.c_str(), length, it->second.size); add.push_back(name); } delete pTemp; } else { printf("file %s will be added\n",name.c_str()); add.push_back(name); } } while (FindNextFileA(hfine, &finddata)); } FindClose(hfine); }
static HANDLE MyFindFirstFile(const std::string& path, LPWIN32_FIND_DATAA findData) { HANDLE hFind = FindFirstFileA(path.c_str(), findData); return hFind; }
void *I_FindFirst(const char *filespec, findstate_t *fileinfo) { return FindFirstFileA(filespec, (LPWIN32_FIND_DATAA)fileinfo); }
bool game::load_next_theme(const bool direction) { vector<string> themes; #ifdef WIN32 string find_path = PW_GAMEDATADIR; find_path += "*" PW_THEME_FILE_EXT; WIN32_FIND_DATAA find_data; HANDLE find_handle = FindFirstFileA(find_path.c_str(), &find_data); if (find_handle != INVALID_HANDLE_VALUE) { do { if (!(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) themes.push_back(find_data.cFileName); } while (FindNextFileA(find_handle, &find_data)); FindClose(find_handle); } #else DIR* dir = opendir(PW_GAMEDATADIR); if (dir) { dirent* ent = NULL; while ((ent = readdir(dir))) { if (strstr(ent->d_name, PW_THEME_FILE_EXT)) themes.push_back(ent->d_name); } closedir(dir); } #endif //WIN32 const size_t themes_sz = themes.size(); if (themes_sz == 0) return false; //Not themes found? //Find current position const string curr_theme_file = string(settings::theme()) + PW_THEME_FILE_EXT; int curr_theme_id = -1; for (size_t i = 0; curr_theme_id < 0 && i < themes_sz; ++i) { if (themes[i].compare(curr_theme_file) == 0) curr_theme_id = static_cast<int>(i); } //Try to load next available theme int try_count = static_cast<int>(themes_sz); while (--try_count >= 0) { string new_theme_file = PW_GAMEDATADIR; if (curr_theme_id < 0) new_theme_file += themes.front(); //Current theme not found else { curr_theme_id += (direction ? 1 : -1); if (curr_theme_id < 0) curr_theme_id = static_cast<int>(themes_sz - 1); else if (curr_theme_id >= static_cast<int>(themes_sz)) curr_theme_id = 0; new_theme_file += themes[curr_theme_id]; } if (render::instance().load(new_theme_file.c_str())) { string theme_name = new_theme_file; theme_name.erase(0, theme_name.find_last_of("\\/") + 1); //Erase path theme_name.erase(theme_name.length() - 4); //Erase file extension settings::theme(theme_name.c_str()); break; } } return try_count >= 0; }
/* Lately, dirSpec appears to be (rightfully) unused. */ __private_extern__ CFMutableArrayRef _CFContentsOfDirectory(CFAllocatorRef alloc, char *dirPath, void *dirSpec, CFURLRef dirURL, CFStringRef matchingAbstractType) { CFMutableArrayRef files = NULL; Boolean releaseBase = false; CFIndex pathLength = dirPath ? (CFIndex)strlen(dirPath) : 0; // MF:!!! Need to use four-letter type codes where appropriate. CFStringRef extension = (matchingAbstractType ? _CFCopyExtensionForAbstractType(matchingAbstractType) : NULL); CFIndex extLen = (extension ? CFStringGetLength(extension) : 0); uint8_t extBuff[CFMaxPathSize]; if (extLen > 0) { CFStringGetBytes(extension, CFRangeMake(0, extLen), CFStringFileSystemEncoding(), 0, false, extBuff, CFMaxPathLength, &extLen); extBuff[extLen] = '\0'; } uint8_t pathBuf[CFMaxPathSize]; if (!dirPath) { if (!CFURLGetFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) { if (extension) CFRelease(extension); return NULL; } else { dirPath = (char *)pathBuf; pathLength = (CFIndex)strlen(dirPath); } } #if (DEPLOYMENT_TARGET_MACOSX) || defined(__svr4__) || defined(__hpux__) || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD struct dirent buffer; struct dirent *dp; int err; int no_hang_fd = open("/dev/autofs_nowait", 0); DIR *dirp = opendir(dirPath); if (!dirp) { if (extension) { CFRelease(extension); } close(no_hang_fd); return NULL; // raiseErrno("opendir", path); } files = CFArrayCreateMutable(alloc, 0, & kCFTypeArrayCallBacks); while((0 == readdir_r(dirp, &buffer, &dp)) && dp) { CFURLRef fileURL; unsigned namelen = strlen(dp->d_name); // skip . & ..; they cause descenders to go berserk if (dp->d_name[0] == '.' && (namelen == 1 || (namelen == 2 && dp->d_name[1] == '.'))) { continue; } if (extLen > namelen) continue; // if the extension is the same length or longer than the name, it can't possibly match. if (extLen > 0) { // Check to see if it matches the extension we're looking for. if (strncmp(&(dp->d_name[namelen - extLen]), (char *)extBuff, extLen) != 0) { continue; } } if (dirURL == NULL) { dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (uint8_t *)dirPath, pathLength, true); releaseBase = true; } if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN) { Boolean isDir = (dp->d_type == DT_DIR); if (!isDir) { // Ugh; must stat. char subdirPath[CFMaxPathLength]; struct stat statBuf; strlcpy(subdirPath, dirPath, sizeof(subdirPath)); strlcat(subdirPath, "/", sizeof(subdirPath)); strlcat(subdirPath, dp->d_name, sizeof(subdirPath)); if (stat(subdirPath, &statBuf) == 0) { isDir = ((statBuf.st_mode & S_IFMT) == S_IFDIR); } } fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, namelen, isDir, dirURL); } else { fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, namelen, false, dirURL); } CFArrayAppendValue(files, fileURL); CFRelease(fileURL); } err = closedir(dirp); close(no_hang_fd); if (err != 0) { CFRelease(files); if (releaseBase) { CFRelease(dirURL); } if (extension) { CFRelease(extension); } return NULL; } #elif DEPLOYMENT_TARGET_WINDOWS WIN32_FIND_DATAA file; HANDLE handle; if (pathLength + 2 >= CFMaxPathLength) { if (extension) { CFRelease(extension); } return NULL; } if (NULL != dirPath) { dirPath[pathLength] = '\''; dirPath[pathLength + 1] = '*'; dirPath[pathLength + 2] = '\0'; handle = FindFirstFileA(dirPath, &file); if (INVALID_HANDLE_VALUE == handle) { dirPath[pathLength] = '\0'; if (extension) { CFRelease(extension); } return NULL; } } else { pathLength = 0; } files = CFArrayCreateMutable(alloc, 0, &kCFTypeArrayCallBacks); do { CFURLRef fileURL; CFIndex namelen = (CFIndex)strlen(file.cFileName); if (file.cFileName[0] == '.' && (namelen == 1 || (namelen == 2 && file.cFileName[1] == '.'))) { continue; } if (extLen > 0) { // Check to see if it matches the extension we're looking for. if (_stricmp((char*)&(file.cFileName[namelen - extLen]), (char*)extBuff) != 0) { continue; } } if (dirURL == NULL) { dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (UInt8*)dirPath, pathLength, true); releaseBase = true; } // MF:!!! What about the trailing slash? fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (UInt8*)file.cFileName, namelen, false, dirURL); CFArrayAppendValue(files, fileURL); CFRelease(fileURL); } while (FindNextFileA(handle, &file)); FindClose(handle); dirPath[pathLength] = '\0'; #else #error _CFContentsOfDirectory() unknown architechture, not implemented #endif if (extension) { CFRelease(extension); } if (releaseBase) { CFRelease(dirURL); } return files; }
void ListDir(const std::string& path, bool directories, void (*CallBack)(const std::string& filename, void* param), void* param, std::list<std::string> *liste) { // Pfad zum Ordner, wo die Dateien gesucht werden sollen std::string rpath = path.substr(0, path.find_last_of('/') + 1); // Pfad in Kleinbuchstaben umwandeln std::string filen(path); std::transform(path.begin(), path.end(), filen.begin(), tolower); //LOG.lprintf("%s\n", filen.c_str()); // Dateiendung merken size_t pos = path.find_last_of('.'); if(pos == std::string::npos) return; std::string endung = path.substr(pos + 1); #ifdef _WIN32 HANDLE hFile; WIN32_FIND_DATAA wfd; hFile = FindFirstFileA(path.c_str(), &wfd); if(hFile != INVALID_HANDLE_VALUE) { do { std::string whole_path = rpath + wfd.cFileName; bool push = true; if(!directories && ( (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) ) push = false; if(push) { if(CallBack) CallBack(whole_path.c_str(), param); if(liste) liste->push_back(whole_path); } } while(FindNextFileA(hFile, &wfd)); FindClose(hFile); } #else DIR* dir_d; dirent* dir = NULL; if ((dir_d = opendir(rpath.c_str())) != NULL) { while( (dir = readdir(dir_d)) != NULL) { struct stat file_stat; std::string whole_path = rpath + dir->d_name; stat(whole_path.c_str(), &file_stat); bool push = true; if(!directories && S_ISDIR(file_stat.st_mode)) push = false; if(push) { std::string ende = dir->d_name; size_t pos = ende.find_last_of('.'); if(pos == std::string::npos) continue; ende = ende.substr(pos + 1); if(endung != ende) std::transform(ende.begin(), ende.end(), ende.begin(), tolower); //LOG.lprintf("%s == %s\n", endung.c_str(), ende.c_str()); if(endung != ende) continue; if(CallBack) CallBack(whole_path, param); if(liste) liste->push_back(whole_path); } } closedir(dir_d); if(liste) liste->sort(); } #endif // _WIN32 }
static HRESULT DELNODE_recurse_dirtree(LPSTR fname, DWORD flags) { DWORD fattrs = GetFileAttributesA(fname); HRESULT ret = E_FAIL; if (fattrs & FILE_ATTRIBUTE_DIRECTORY) { HANDLE hFindFile; WIN32_FIND_DATAA w32fd; BOOL done = TRUE; int fname_len = lstrlenA(fname); /* Generate a path with wildcard suitable for iterating */ if (fname[fname_len - 1] != '\\') { lstrcpyA(fname + fname_len, "\\"); ++fname_len; } lstrcpyA(fname + fname_len, "*"); if ((hFindFile = FindFirstFileA(fname, &w32fd)) != INVALID_HANDLE_VALUE) { /* Iterate through the files in the directory */ for (done = FALSE; !done; done = !FindNextFileA(hFindFile, &w32fd)) { TRACE("%s\n", w32fd.cFileName); if (lstrcmpA(".", w32fd.cFileName) != 0 && lstrcmpA("..", w32fd.cFileName) != 0) { lstrcpyA(fname + fname_len, w32fd.cFileName); if (DELNODE_recurse_dirtree(fname, flags) != S_OK) { break; /* Failure */ } } } FindClose(hFindFile); } /* We're done with this directory, so restore the old path without wildcard */ *(fname + fname_len) = '\0'; if (done) { TRACE("%s: directory\n", fname); if (SetFileAttributesA(fname, FILE_ATTRIBUTE_NORMAL) && RemoveDirectoryA(fname)) { ret = S_OK; } } } else { TRACE("%s: file\n", fname); if (SetFileAttributesA(fname, FILE_ATTRIBUTE_NORMAL) && DeleteFileA(fname)) { ret = S_OK; } } return ret; }
void Gource::findUserImages() { if(!gGourceUserImageDir.size()) return; #ifdef _WIN32 HANDLE hList; char szDir[MAX_PATH+1]; WIN32_FIND_DATAA FileData; // Get the proper directory path sprintf(szDir, "%s\\*", gGourceUserImageDir.c_str()); // Get the first file hList = FindFirstFileA(szDir, &FileData); if (hList == INVALID_HANDLE_VALUE) { debugLog("No files found\n\n"); return; } else { // Traverse through the directory structure for (;;) { // Check the object is a directory or not if ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { std::string dirfile(FileData.cFileName); size_t extpos = 0; if ((extpos=dirfile.rfind(".jpg")) != std::string::npos || (extpos=dirfile.rfind(".jpeg")) != std::string::npos || (extpos=dirfile.rfind(".png")) != std::string::npos) { std::string image_path = gGourceUserImageDir + dirfile; std::string name = dirfile.substr(0,extpos); debugLog("%s => %s\n", name.c_str(), image_path.c_str()); gGourceUserImageMap[name] = image_path; } } // get the next file if (!FindNextFileA(hList, &FileData)) { if (GetLastError() == ERROR_NO_MORE_FILES) { break; } } } } FindClose(hList); #else //get jpg and png images in dir DIR *dp; struct dirent *dirp; if((dp = opendir(gGourceUserImageDir.c_str())) == 0) return; while ((dirp = readdir(dp)) != 0) { std::string dirfile = std::string(dirp->d_name); int extpos = 0; if( (extpos=dirfile.rfind(".jpg")) == std::string::npos && (extpos=dirfile.rfind(".jpeg")) == std::string::npos && (extpos=dirfile.rfind(".png")) == std::string::npos) continue; std::string image_path = gGourceUserImageDir + dirfile; std::string name = dirfile.substr(0,extpos); debugLog("%s => %s\n", name.c_str(), image_path.c_str()); gGourceUserImageMap[name] = image_path; } closedir(dp); #endif }
void __PHYSFS_platformEnumerateFiles(const char *dirname, int omitSymLinks, PHYSFS_EnumFilesCallback callback, const char *origdir, void *callbackdata) { const int unicode = (pFindFirstFileW != NULL) && (pFindNextFileW != NULL); HANDLE dir = INVALID_HANDLE_VALUE; WIN32_FIND_DATA ent; WIN32_FIND_DATAW entw; size_t len = strlen(dirname); char *searchPath = NULL; WCHAR *wSearchPath = NULL; char *utf8 = NULL; /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */ searchPath = (char *) __PHYSFS_smallAlloc(len + 3); if (searchPath == NULL) return; /* Copy current dirname */ strcpy(searchPath, dirname); /* if there's no '\\' at the end of the path, stick one in there. */ if (searchPath[len - 1] != '\\') { searchPath[len++] = '\\'; searchPath[len] = '\0'; } /* if */ /* Append the "*" to the end of the string */ strcat(searchPath, "*"); UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath); if (wSearchPath == NULL) return; /* oh well. */ if (unicode) dir = pFindFirstFileW(wSearchPath, &entw); else { const int len = (int) (wStrLen(wSearchPath) + 1); char *cp = (char *) __PHYSFS_smallAlloc(len); if (cp != NULL) { WideCharToMultiByte(CP_ACP, 0, wSearchPath, len, cp, len, 0, 0); dir = FindFirstFileA(cp, &ent); __PHYSFS_smallFree(cp); } /* if */ } /* else */ __PHYSFS_smallFree(wSearchPath); __PHYSFS_smallFree(searchPath); if (dir == INVALID_HANDLE_VALUE) return; if (unicode) { do { const DWORD attr = entw.dwFileAttributes; const DWORD tag = entw.dwReserved0; const WCHAR *fn = entw.cFileName; if ((fn[0] == '.') && (fn[1] == '\0')) continue; if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0')) continue; if ((omitSymLinks) && (isSymlinkAttrs(attr, tag))) continue; utf8 = unicodeToUtf8Heap(fn); if (utf8 != NULL) { callback(callbackdata, origdir, utf8); allocator.Free(utf8); } /* if */ } while (pFindNextFileW(dir, &entw) != 0); } /* if */ else /* ANSI fallback. */ { do { const DWORD attr = ent.dwFileAttributes; const DWORD tag = ent.dwReserved0; const char *fn = ent.cFileName; if ((fn[0] == '.') && (fn[1] == '\0')) continue; if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0')) continue; if ((omitSymLinks) && (isSymlinkAttrs(attr, tag))) continue; utf8 = codepageToUtf8Heap(fn); if (utf8 != NULL) { callback(callbackdata, origdir, utf8); allocator.Free(utf8); } /* if */ } while (FindNextFileA(dir, &ent) != 0); } /* else */ FindClose(dir); } /* __PHYSFS_platformEnumerateFiles */
void fs__readdir(uv_fs_t* req, const char* path, int flags) { int result; char* buf, *ptr, *name; HANDLE dir; WIN32_FIND_DATAA ent = {0}; size_t len = strlen(path); size_t buf_size = 4096; const char* fmt = !len ? "./*" : (path[len - 1] == '/' || path[len - 1] == '\\') ? "%s*" : "%s\\*"; char* path2 = (char*)malloc(len + 4); if (!path2) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } sprintf(path2, fmt, path); dir = FindFirstFileA(path2, &ent); free(path2); if(dir == INVALID_HANDLE_VALUE) { result = -1; goto done; } buf = (char*)malloc(buf_size); if (!buf) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } ptr = buf; result = 0; do { name = ent.cFileName; if (name[0] != '.' || (name[1] && (name[1] != '.' || name[2]))) { len = strlen(name); while ((ptr - buf) + len + 1 > buf_size) { buf_size *= 2; path2 = buf; buf = (char*)realloc(buf, buf_size); if (!buf) { uv_fatal_error(ERROR_OUTOFMEMORY, "realloc"); } ptr = buf + (ptr - path2); } strcpy(ptr, name); ptr += len + 1; result++; } } while(FindNextFileA(dir, &ent)); FindClose(dir); req->ptr = buf; req->flags |= UV_FS_FREE_PTR; done: SET_REQ_RESULT(req, result); }
void main (int argc, char *argv[]) { WIN32_FIND_DATAA ffd; HANDLE h_find; char file_pattern[MAX_PATH]; if (argc != 3) { printf("patmake.exe <mol-root> <cpp-output>"); return; } if (argv[1][strlen(argv[1]) - 1] == '\\') argv[1][strlen(argv[1]) - 1] = 0; sprintf_s(file_pattern, "%s\\*.mol", argv[1]); h_find = FindFirstFileA(file_pattern, &ffd); if (h_find == INVALID_HANDLE_VALUE) { printf ("FindFirstFile failed (%d)\n", GetLastError()); return; } else { try { FileOutput cpp_file(true, argv[2]); SYSTEMTIME st; GetSystemTime(&st); char buf[200]; sprintf_s(buf, " * Added %02d/%02d/%02d %02d:%02d:%02d", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond); cpp_file.writeStringCR("/*"); cpp_file.writeStringCR(buf); cpp_file.writeStringCR(" */"); do { try { convertMolfile(argv[1], ffd.cFileName, cpp_file); } catch (Exception &e) { printf("Error: %s\n", e.message()); } } while (FindNextFileA(h_find, &ffd) != 0); printf("Done.\n"); } catch (Exception &e) { printf("Error: %s\n", e.message()); } FindClose(h_find); } }
/* This callback gets invoked when we get any http request that doesn't match * any other callback. Like any evhttp server callback, it has a simple job: * it must eventually call evhttp_send_error() or evhttp_send_reply(). */ static void send_document_cb(struct evhttp_request *req, void *arg) { struct evbuffer *evb = NULL; const char *docroot = (const char *)arg; const char *uri = evhttp_request_get_uri(req); struct evhttp_uri *decoded = NULL; const char *path; char *decoded_path; char *whole_path = NULL; size_t len; int fd = -1; struct stat st; if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { dump_request_cb(req, arg); return; } printf("Got a GET request for <%s>\n", uri); /* Decode the URI */ decoded = evhttp_uri_parse(uri); if (!decoded) { printf("It's not a good URI. Sending BADREQUEST\n"); evhttp_send_error(req, HTTP_BADREQUEST, 0); return; } /* Let's see what path the user asked for. */ path = evhttp_uri_get_path(decoded); if (!path) path = "/"; /* We need to decode it, to see what path the user really wanted. */ decoded_path = evhttp_uridecode(path, 0, NULL); if (decoded_path == NULL) goto err; /* Don't allow any ".."s in the path, to avoid exposing stuff outside * of the docroot. This test is both overzealous and underzealous: * it forbids aceptable paths like "/this/one..here", but it doesn't * do anything to prevent symlink following." */ if (strstr(decoded_path, "..")) goto err; len = strlen(decoded_path)+strlen(docroot)+2; if (!(whole_path = (char *)malloc(len))) { perror("malloc"); goto err; } evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path); if (stat(whole_path, &st)<0) { goto err; } /* This holds the content we're sending. */ evb = evbuffer_new(); if (S_ISDIR(st.st_mode)) { /* If it's a directory, read the comments and make a little * index page */ #ifdef WIN32 HANDLE d; WIN32_FIND_DATAA ent; char *pattern; size_t dirlen; #else DIR *d; struct dirent *ent; #endif const char *trailing_slash = ""; if (!strlen(path) || path[strlen(path)-1] != '/') trailing_slash = "/"; #ifdef WIN32 dirlen = strlen(whole_path); pattern = malloc(dirlen+3); memcpy(pattern, whole_path, dirlen); pattern[dirlen] = '\\'; pattern[dirlen+1] = '*'; pattern[dirlen+2] = '\0'; d = FindFirstFileA(pattern, &ent); free(pattern); if (d == INVALID_HANDLE_VALUE) goto err; #else if (!(d = opendir(whole_path))) goto err; #endif evbuffer_add_printf(evb, "<html>\n <head>\n" " <title>%s</title>\n" " <base href='%s%s%s'>\n" " </head>\n" " <body>\n" " <h1>%s</h1>\n" " <ul>\n", decoded_path, /* XXX html-escape this. */ uri_root, path, /* XXX html-escape this? */ trailing_slash, decoded_path /* XXX html-escape this */); #ifdef WIN32 do { const char *name = ent.cFileName; #else while ((ent = readdir(d))) { const char *name = ent->d_name; #endif evbuffer_add_printf(evb, " <li><a href=\"%s\">%s</a>\n", name, name);/* XXX escape this */ #ifdef WIN32 } while (FindNextFileA(d, &ent)); #else } #endif evbuffer_add_printf(evb, "</ul></body></html>\n"); #ifdef WIN32 CloseHandle(d); #else closedir(d); #endif evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html"); } else {
int __cdecl main(int argc, char *argv[]) { WIN32_FIND_DATA findFileData; HANDLE hFind = NULL; FILE *pFile = NULL; BOOL bRc = FALSE; WCHAR* szwTemp = NULL; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } // // find a file with a NULL pointer // hFind = FindFirstFileA(NULL, &findFileData); if (hFind != INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Found invalid NULL file"); } // // find a file that doesn't exist // hFind = FindFirstFileA(szNoFileName, &findFileData); if (hFind != INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Found invalid NULL file"); } // // find a file that exists // pFile = fopen(szFindName, "w"); if (pFile == NULL) { Fail("FindFirstFileA: ERROR -> Unable to create a test file\n"); } else { fclose(pFile); } hFind = FindFirstFileA(szFindName, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Unable to find \"%s\"\n", szFindName); } else { // validate we found the correct file if (strcmp(szFindName, findFileData.cFileName) != 0) { Fail ("FindFirstFileA: ERROR -> Found the wrong file\n"); } } // // find a directory that exists // szwTemp = convert((LPSTR)szDirName); bRc = CreateDirectoryW(szwTemp, NULL); free(szwTemp); if (bRc == FALSE) { Fail("FindFirstFileA: ERROR -> Failed to create the directory " "\"%s\"\n", szDirName); } hFind = FindFirstFileA(szDirName, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR. Unable to find \"%s\"\n", szDirName); } else { // validate we found the correct directory if (strcmp(szDirName, findFileData.cFileName) != 0) { Fail ("FindFirstFileA: ERROR -> Found the wrong directory\n"); } } // // find a directory using a trailing '\' on the directory name: should fail // hFind = FindFirstFileA(szDirNameSlash, &findFileData); if (hFind != INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Able to find \"%s\": trailing " "slash should have failed.\n", szDirNameSlash); } // find a file using wild cards hFind = FindFirstFileA(szFindNameWldCard_01, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Unable to find \"%s\"\n", szFindNameWldCard_01); } hFind = FindFirstFileA(szFindNameWldCard_02, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Unable to find \"%s\"\n", szFindNameWldCard_02); } // // find a directory using wild cards // hFind = FindFirstFileA(szDirNameWldCard_01, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Unable to find \"%s\"\n", szDirNameWldCard_01); } hFind = FindFirstFileA(szDirNameWldCard_02, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { Fail ("FindFirstFileA: ERROR -> Unable to find \"%s\"\n", szDirNameWldCard_02); } szwTemp = convert((LPSTR)szDirName); RemoveDirectoryW(szwTemp); free(szwTemp); DeleteFileA(szFindName); PAL_Terminate(); return PASS; }
zdir_t * zdir_new (const char *path, const char *parent) { zdir_t *self = (zdir_t *) zmalloc (sizeof (zdir_t)); if (!self) return NULL; if (parent) { if (streq (parent, "-")) { self->trimmed = true; self->path = strdup (path); } else { self->path = (char *) malloc (strlen (path) + strlen (parent) + 2); if (self->path) sprintf (self->path, "%s/%s", parent, path); } } else self->path = strdup (path); if (self->path) self->files = zlist_new (); if (self->files) self->subdirs = zlist_new (); if (!self->subdirs) { zdir_destroy (&self); return NULL; } #if (defined (WIN32)) // On Windows, replace backslashes by normal slashes char *path_clean_ptr = self->path; while (*path_clean_ptr) { if (*path_clean_ptr == '\\') *path_clean_ptr = '/'; path_clean_ptr++; } // Remove any trailing slash if (self->path [strlen (self->path) - 1] == '/') self->path [strlen (self->path) - 1] = 0; // Win32 wants a wildcard at the end of the path char *wildcard = (char *) malloc (strlen (self->path) + 3); if (!wildcard) { zdir_destroy (&self); return NULL; } sprintf (wildcard, "%s/*", self->path); WIN32_FIND_DATAA entry; HANDLE handle = FindFirstFileA (wildcard, &entry); free (wildcard); if (handle != INVALID_HANDLE_VALUE) { // We have read an entry, so return those values s_win32_populate_entry (self, &entry); while (FindNextFileA (handle, &entry)) s_win32_populate_entry (self, &entry); FindClose (handle); } #else // Remove any trailing slash if (self->path [strlen (self->path) - 1] == '/') self->path [strlen (self->path) - 1] = 0; DIR *handle = opendir (self->path); if (handle) { // Calculate system-specific size of dirent block int dirent_size = offsetof (struct dirent, d_name) + pathconf (self->path, _PC_NAME_MAX) + 1; struct dirent *entry = (struct dirent *) malloc (dirent_size); struct dirent *result; int rc = readdir_r (handle, entry, &result); while (rc == 0 && result != NULL) { s_posix_populate_entry (self, entry); rc = readdir_r (handle, entry, &result); } free (entry); closedir (handle); } #endif else {
static int DoRemoveDirectory( Tcl_DString *pathPtr, /* Pathname of directory to be removed * (native). */ int recursive, /* If non-zero, removes directories that * are nonempty. Otherwise, will only remove * empty directories. */ Tcl_DString *errorPtr) /* If non-NULL, uninitialized or free * DString filled with UTF-8 name of file * causing error. */ { CONST TCHAR *nativePath; DWORD attr; nativePath = (TCHAR *) Tcl_DStringValue(pathPtr); if ((*tclWinProcs->removeDirectoryProc)(nativePath) != FALSE) { return TCL_OK; } TclWinConvertError(GetLastError()); /* * Win32s thinks that "" is the same as "." and then reports EACCES * instead of ENOENT. */ if (tclWinProcs->useWide) { if (((WCHAR *) nativePath)[0] == '\0') { Tcl_SetErrno(ENOENT); return TCL_ERROR; } } else { if (((char *) nativePath)[0] == '\0') { Tcl_SetErrno(ENOENT); return TCL_ERROR; } } if (Tcl_GetErrno() == EACCES) { attr = (*tclWinProcs->getFileAttributesProc)(nativePath); if (attr != 0xffffffff) { if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) { /* * Windows 95 reports calling RemoveDirectory on a file as an * EACCES, not an ENOTDIR. */ Tcl_SetErrno(ENOTDIR); goto end; } if (attr & FILE_ATTRIBUTE_READONLY) { attr &= ~FILE_ATTRIBUTE_READONLY; if ((*tclWinProcs->setFileAttributesProc)(nativePath, attr) == FALSE) { goto end; } if ((*tclWinProcs->removeDirectoryProc)(nativePath) != FALSE) { return TCL_OK; } TclWinConvertError(GetLastError()); (*tclWinProcs->setFileAttributesProc)(nativePath, attr | FILE_ATTRIBUTE_READONLY); } /* * Windows 95 and Win32s report removing a non-empty directory * as EACCES, not EEXIST. If the directory is not empty, * change errno so caller knows what's going on. */ if (TclWinGetPlatformId() != VER_PLATFORM_WIN32_NT) { char *path, *find; HANDLE handle; WIN32_FIND_DATAA data; Tcl_DString buffer; int len; path = (char *) nativePath; Tcl_DStringInit(&buffer); len = strlen(path); find = Tcl_DStringAppend(&buffer, path, len); if ((len > 0) && (find[len - 1] != '\\')) { Tcl_DStringAppend(&buffer, "\\", 1); } find = Tcl_DStringAppend(&buffer, "*.*", 3); handle = FindFirstFileA(find, &data); if (handle != INVALID_HANDLE_VALUE) { while (1) { if ((strcmp(data.cFileName, ".") != 0) && (strcmp(data.cFileName, "..") != 0)) { /* * Found something in this directory. */ Tcl_SetErrno(EEXIST); break; } if (FindNextFileA(handle, &data) == FALSE) { break; } } FindClose(handle); } Tcl_DStringFree(&buffer); } } } if (Tcl_GetErrno() == ENOTEMPTY) { /* * The caller depends on EEXIST to signify that the directory is * not empty, not ENOTEMPTY. */ Tcl_SetErrno(EEXIST); } if ((recursive != 0) && (Tcl_GetErrno() == EEXIST)) { /* * The directory is nonempty, but the recursive flag has been * specified, so we recursively remove all the files in the directory. */ return TraverseWinTree(TraversalDelete, pathPtr, NULL, errorPtr); } end: if (errorPtr != NULL) { Tcl_WinTCharToUtf(nativePath, -1, errorPtr); } return TCL_ERROR; }