CFileList::CFileList() { #ifdef _DEBUG setDebugName("CFileList"); #endif // -------------------------------------------- // Windows version #ifdef _IRR_WINDOWS_API_ char tmp[_MAX_PATH]; _getcwd(tmp, _MAX_PATH); Path = tmp; struct _finddata_t c_file; long hFile; FileEntry entry; if( (hFile = _findfirst( "*", &c_file )) != -1L ) { do { entry.Name = c_file.name; entry.Size = c_file.size; entry.isDirectory = (_A_SUBDIR & c_file.attrib) != 0; Files.push_back(entry); } while( _findnext( hFile, &c_file ) == 0 ); _findclose( hFile ); } //TODO add drives //entry.Name = "E:\\"; //entry.isDirectory = true; //Files.push_back(entry); #endif // -------------------------------------------- // Linux version #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_)) FileEntry entry; // Add default parent - even when at /, this is available entry.Name = ".."; entry.Size = 0; entry.isDirectory = true; Files.push_back(entry); // getting the CWD is rather complex as we do not know the size // so try it until the call was successful // Note that neither the first nor the second parameter may be 0 according to POSIX u32 pathSize=256; char *tmpPath = new char[pathSize]; while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize))) { delete [] tmpPath; pathSize *= 2; tmpPath = new char[pathSize]; } if (!tmpPath) return; Path = tmpPath; delete [] tmpPath; // We use the POSIX compliant methods instead of scandir DIR* dirHandle=opendir(Path.c_str()); if (!dirHandle) return; struct dirent *dirEntry; while ((dirEntry=readdir(dirHandle))) { if((strcmp(dirEntry->d_name, ".")==0) || (strcmp(dirEntry->d_name, "..")==0)) continue; entry.Name = dirEntry->d_name; entry.Size = 0; entry.isDirectory = false; struct stat buf; if (stat(dirEntry->d_name, &buf)==0) { entry.Size = buf.st_size; entry.isDirectory = S_ISDIR(buf.st_mode); } #if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__) // only available on some systems else { entry.isDirectory = dirEntry->d_type == DT_DIR; } #endif Files.push_back(entry); } closedir(dirHandle); #endif // sort the list on all platforms Files.sort(); }
/* ======================================================================== PURPOSE : Searches through the pathName directory for files matching the wildcard baseName.* and fills in all the data to the ptrHeader structure. RETURNS : Number of files encoded into the header. HISTORY: @1 */ static int genHeader (const char *pathName, const char *baseName, const char *extName, stJAndSHeader *ptrHeader, char dir_flag) //@3 { char wildcardName[_MAX_DIR], joinFileName[_MAX_DIR]; //struct find_t // fileinfo; struct _finddata_t fileinfo; unsigned rc = 0; /* return code */ // No files found yet (ptrHeader->numFilesJoined) = 0; // Generate the wild card name to match against if (dir_flag == 1) { //@3 if (strlen(pathName)) sprintf (wildcardName, "%s\\*.*", pathName); else sprintf (wildcardName, ".\\*.*"); } else { if (strlen(pathName)) sprintf (wildcardName, "%s\\%s.*", pathName, baseName); else sprintf (wildcardName, ".\\%s.*", baseName); } // Generate name of the join file _snprintf (joinFileName, 200, "%s%s", baseName, extName); // Search for all files matching the wildcard //rc = _dos_findfirst (wildcardName, _A_NORMAL, &fileinfo ); auto handle = _findfirst(wildcardName, &fileinfo); if (handle != -1) { // Get the data for each file found upto max that can be stored //while ((rc == 0) && // (ptrHeader->numFilesJoined < MAX_FILES_JOINED)) do { // Don't include files with the same extension as the join file if (_stricmp(joinFileName, fileinfo.name) != 0 && fileinfo.size > 0 ) { // Copy the file information to the header _snprintf (ptrHeader->fileName[ptrHeader->numFilesJoined],15, fileinfo.name); ptrHeader->fileLen[ptrHeader->numFilesJoined] = fileinfo.size; (ptrHeader->numFilesJoined)++; } // Look for the next file in the directory //rc = _dos_findnext( &fileinfo ); rc = _findnext(handle, &fileinfo); } while ((rc == 0) && (ptrHeader->numFilesJoined < MAX_FILES_JOINED)); _findclose(handle); } //@5 if ((rc == 0)&&(ptrHeader->numFilesJoined == MAX_FILES_JOINED)) { // Don't include files with the same extension as the join file if (_stricmp(joinFileName, fileinfo.name) != 0) { throw std::exception ("Too many files joined!!!" ); } } return ptrHeader->numFilesJoined; }
UINT CSADirRead::FindFiles(const CCOMString & dir, const CCOMString & filter, bool bIncludeFilesInFileList, bool bIncludeFoldersInFileList) { // make sure the path ends in a single "\" CCOMString baseName = dir; FormatPath(baseName); baseName+='\\'; CCOMString fullPath = baseName; fullPath += filter; CCOMString fileName; // find first file in current directory #ifndef USE_WIN32_FINDFILE struct _finddata_t c_file; long fhandle; try { if ((fhandle=_findfirst( fullPath, &c_file ))!=-1) { bool bIsFolder = (c_file.attrib & _A_SUBDIR)==_A_SUBDIR; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || (!bIsFolder && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(c_file.name, ".")==0) || (strcmp(c_file.name, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName = baseName; fileName += c_file.name; CSAFileEntry t; t.bIsFolder = bIsFolder; t.attrib = c_file.attrib; t.m_sName = fileName; t.time_write = c_file.time_write; t.time_create = c_file.time_create; t.size = c_file.size; m_files.push_back(t); } // find the rest of them while(_findnext( fhandle, &c_file ) == 0 ) { bool bIsFolder = (c_file.attrib & _A_SUBDIR)==_A_SUBDIR; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || (!bIsFolder && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(c_file.name, ".")==0) || (strcmp(c_file.name, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName=baseName; fileName += c_file.name; CSAFileEntry t; t.bIsFolder = bIsFolder; t.attrib = c_file.attrib; t.m_sName = fileName; t.time_write = c_file.time_write; t.time_create = c_file.time_create; t.size = c_file.size; m_files.push_back(t); } } _findclose(fhandle); } } catch (...) { return false; } #else WIN32_FIND_DATA FindFileData; HANDLE hFind; try { if ((hFind = FindFirstFile(fullPath, &FindFileData))!=INVALID_HANDLE_VALUE) { bool bIsFolder = (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || ((!bIsFolder) && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(FindFileData.cFileName, ".")==0) || (strcmp(FindFileData.cFileName, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName = baseName; fileName += FindFileData.cFileName; CSAFileEntry t; t.m_sName = fileName; t.bIsFolder = bIsFolder; t.attrib = FindFileData.dwFileAttributes; memcpy(&t.time_write, &FindFileData.ftLastWriteTime, sizeof(_FILETIME)); memcpy(&t.time_create, &FindFileData.ftCreationTime, sizeof(_FILETIME)); t.size = ((unsigned __int64)FindFileData.nFileSizeHigh * ((unsigned __int64)MAXDWORD+1)) + (unsigned __int64)FindFileData.nFileSizeLow; m_files.push_back(t); } // find the rest of them while (FindNextFile(hFind, &FindFileData)) { bool bIsFolder = (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY; bool bAddThisOne = (bIsFolder && bIncludeFoldersInFileList) || ((!bIsFolder) && bIncludeFilesInFileList); // skip . and .. if (bIsFolder && (strcmp(FindFileData.cFileName, ".")==0) || (strcmp(FindFileData.cFileName, "..")==0)) { bAddThisOne = false; } if (bAddThisOne) { fileName = baseName; fileName += FindFileData.cFileName; CSAFileEntry t; t.m_sName = fileName; t.bIsFolder = bIsFolder; t.attrib = FindFileData.dwFileAttributes; memcpy(&t.time_write, &FindFileData.ftLastWriteTime, sizeof(_FILETIME)); memcpy(&t.time_create, &FindFileData.ftCreationTime, sizeof(_FILETIME)); t.size = ((unsigned __int64)FindFileData.nFileSizeHigh * ((unsigned __int64)MAXDWORD+1)) + (unsigned __int64)FindFileData.nFileSizeLow; m_files.push_back(t); } } FindClose(hFind); } } catch (...) { return false; } #endif return true; }
void ModuleLoader::setModuleDirectory(const char* directory) { const size_t len = strlen(directory) + 256 + 1; char pattern[1024]; strcpy(pattern, directory); strcat(pattern, "/*.*"); _finddata_t data; intptr_t dir = _findfirst(pattern, &data); if(!dir) return; char* fname; IServiceManager* servmgr; fname = static_cast<char*>(malloc(len)); servmgr = XPLC::getServiceManager(); bool first = true; while(fname && servmgr) { if(!first && _findnext(dir, &data)) break; first = false; const char* err; void* dlh; XPLC_GetModuleFunc getmodule = 0; IModule* module; ModuleNode* newmodule; _snprintf(fname, len, "%s/%s", directory, data.name); err = loaderOpen(fname, &dlh); if(err) continue; err = loaderSymbol(dlh, "XPLC_GetModule", reinterpret_cast<void**>(&getmodule)); if(err || !getmodule) { loaderClose(dlh); continue; } module = getmodule(servmgr, XPLC_MODULE_VERSION); if(!module) { loaderClose(dlh); continue; } newmodule = new ModuleNode(module, dlh, modules); if(newmodule) modules = newmodule; } if(servmgr) servmgr->release(); free(fname); _findclose(dir); }
// LoadDataset: Loads dataset from disk to memory ImageDataset* CPCAUtils::LoadDataset(char *directory) { //aux variables long l; int i=0; unsigned int TotalImages=0; bool bojpg=false; ImageDataset *Dataset=(ImageDataset*)new char[sizeof(ImageDataset)]; #ifndef ENCARA2INLINUX struct _finddata_t fi; //moves to directory _chdir(directory); // Checks first dataset size //Counts total number of images in directory l=(long)_findfirst("*.Ipl", &fi); //If not checks for jpg if (l==-1) { l=(long)_findfirst("*.jpg", &fi); bojpg=true; } if (l!=-1) { do { TotalImages++; } while (_findnext(l, &fi)==0); _findclose(l); } #else glob_t fi; //Indica el número de posiciones que aloja fi.gl_offs=MAXFILES; glob("*.Ipl", GLOB_DOOFFS, NULL, &fi); //If not checks for jpg if (l==-1) { glob("*.jpg", GLOB_DOOFFS, NULL, &fi); bojpg=true; } //Guarda el número de imágenes encontradas TotalImages=(int)fi.gl_pathc; globfree(&fi); #endif //If there are no images return if (TotalImages<=0) { delete [] Dataset; return NULL; } //Allocs memory for the dataset images IplImage** BC=(IplImage**) new unsigned char[TotalImages*sizeof(IplImage*)]; //Load images unsigned int Frame=0; #ifndef ENCARA2INLINUX if (!bojpg) l=(long)_findfirst("*.Ipl", &fi); else l=(long)_findfirst("*.jpg", &fi); if (l!=-1) { do { if (!bojpg) BC[Frame] = IplUtils.LoadIplImage(fi.name); #ifndef USES_OF else BC[Frame] = cvLoadImage(fi.name,0); //Fuerza cargar imagen grises #endif Frame++; } while (_findnext(l, &fi)==0); _findclose(l); } #else //Indica el número de posiciones que aloja fi.gl_offs=MAXFILES; if (!bojpg) glob("*.Ipl", GLOB_DOOFFS, NULL, &fi); else glob("*.jpg", GLOB_DOOFFS, NULL, &fi); for (i=0;i<(int)fi.gl_pathc;i++) { if (!bojpg) BC[Frame] = IplUtils.LoadIplImage(fi.gl_pathv[i]); #ifndef USES_OF else BC[Frame] = cvLoadImage(fi.gl_pathv[i],0); //Fuerza cargar imagen grises #endif Frame++; } globfree(&fi); #endif Dataset->BC=BC; Dataset->TotalImages=TotalImages; Dataset->ImageSize=cvSize(BC[0]->width,BC[0]->height); return Dataset; }
/* * Parse and import *.asn1 from skeletons/standard-modules */ static int importStandardModules(asn1p_t *asn, const char *skeletons_dir) { asn1p_t *new_asn; asn1p_module_t *mod; const char *filename; char *fullname; char *target_dir; int target_dir_len; int len; #ifdef _WIN32 intptr_t dir; struct _finddata_t c_file; char *pattern; #else struct dirent *dp; DIR *dir; #endif int ret = 0; /* Notes for the human reader */ assert(asn); assert(skeletons_dir); /* * Figure out the standard-modules directory. */ target_dir_len = strlen(skeletons_dir) + sizeof("/standard-modules") - 1; target_dir = malloc(target_dir_len + 1); assert(target_dir); snprintf(target_dir, target_dir_len + 1, "%s/standard-modules", skeletons_dir); #ifdef _WIN32 len = target_dir_len + sizeof("/*.asn1"); pattern = malloc(len); assert(pattern); snprintf(pattern, len, "%s/*.asn1", target_dir); dir = _findfirst(pattern, &c_file); if(dir == -1L) { #else dir = opendir(target_dir); if(!dir) { #endif fprintf(stderr, "WARNING: Cannot find standard modules in %s\n", target_dir); return -1; } #ifdef _WIN32 do { filename = c_file.name; #else while((dp = readdir(dir))) { filename = dp->d_name; #endif len = strlen(filename); if(len <= 5 || strcmp(filename + len - 5, ".asn1")) continue; len = target_dir_len + 1 + len + 1; fullname = malloc(len); if(!fullname) continue; /* Just skip it, no big deal */ snprintf(fullname, len, "%s/%s", target_dir, filename); filename = fullname; new_asn = asn1p_parse_file(filename, A1P_NOFLAGS); if(new_asn == NULL) { fprintf(stderr, "WARNING: Cannot parse standard module \"%s\"\n", filename); ret = -1; continue; } /* Import these modules and mark them as "standard" */ while((mod = TQ_REMOVE(&(new_asn->modules), mod_next))) { mod->_tags |= MT_STANDARD_MODULE; TQ_ADD(&(asn->modules), mod, mod_next); } asn1p_delete(new_asn); #ifdef _WIN32 } while(_findnext(dir, &c_file) == 0); _findclose(dir); #else free(fullname); } /* while(readdir()) */ closedir(dir); #endif return ret; }
void ExitTileDialog(void) { _findclose(hFile); }
//----------------------------------------------------------------------- void FileSystemArchive::findFiles(const String& pattern, bool recursive, bool dirs, StringVector* simpleList, FileInfoList* detailList) { long lHandle, res; struct _finddata_t tagData; // pattern can contain a directory name, separate it from mask size_t pos1 = pattern.rfind ('/'); size_t pos2 = pattern.rfind ('\\'); if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2))) pos1 = pos2; String directory; if (pos1 != pattern.npos) directory = pattern.substr (0, pos1 + 1); String full_pattern = concatenate_path(mName, pattern); lHandle = _findfirst(full_pattern.c_str(), &tagData); res = 0; while (lHandle != -1 && res != -1) { if ((dirs == ((tagData.attrib & _A_SUBDIR) != 0)) && ( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) && (!dirs || !is_reserved_dir (tagData.name))) { if (simpleList) { simpleList->push_back(directory + tagData.name); } else if (detailList) { FileInfo fi; fi.archive = this; fi.filename = directory + tagData.name; fi.basename = tagData.name; fi.path = directory; fi.compressedSize = tagData.size; fi.uncompressedSize = tagData.size; detailList->push_back(fi); } } res = _findnext( lHandle, &tagData ); } // Close if we found any files if(lHandle != -1) _findclose(lHandle); // Now find directories if (recursive) { String base_dir = mName; if (!directory.empty ()) { base_dir = concatenate_path(mName, directory); // Remove the last '/' base_dir.erase (base_dir.length () - 1); } base_dir.append ("/*"); // Remove directory name from pattern String mask ("/"); if (pos1 != pattern.npos) mask.append (pattern.substr (pos1 + 1)); else mask.append (pattern); lHandle = _findfirst(base_dir.c_str (), &tagData); res = 0; while (lHandle != -1 && res != -1) { if ((tagData.attrib & _A_SUBDIR) && ( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) && !is_reserved_dir (tagData.name)) { // recurse base_dir = directory; base_dir.append (tagData.name).append (mask); findFiles(base_dir, recursive, dirs, simpleList, detailList); } res = _findnext( lHandle, &tagData ); } // Close if we found any files if(lHandle != -1) _findclose(lHandle); } }
BOOL CFolderListCtrl::SetCurFolder( const CSCADString& sFolderPath, bool bForce) { if( !bForce && !m_sFolderPath.CompareNoCase( sFolderPath ) ) return TRUE; Timer.Start(); m_DirChangeListener.SetDir(sFolderPath, m_hWnd); /* SCDefProjInfo proj_info; SCADDefProj::GetInfo( m_Properties.m_DefProj, proj_info ); SCMdl3DSetCameraPos( proj_info.m_ptViewDir, proj_info.m_ptUpOrient ); */ // ReSharper disable once CppEntityAssignedButNoRead extern SCDefProjType ThumbProjection; ThumbProjection = m_Properties.m_DefProj; if(CSCAD3DMdlSettings::Get3DS()) { CSCAD3DMdlSettings::Get3DS()->CancelDraw(); CSCAD3DMdlSettings::Get3DS()->SetStartDrawPos( 0 ); } CreateImageList(); DeleteAllItemsData(); DeleteAllItems(); m_sFolderPath = sFolderPath; m_nItemCount = 0; m_nImageBalance = 0; m_nSelectedItem = -1; SetSelectionMark( 0 ); int i; for( i = m_imlLargeIcons.GetImageCount() - 1; i >= 0; i-- ) m_imlLargeIcons.Remove( i ); for( i = m_imlSmallIcons.GetImageCount() - 1; i >= 0; i-- ) m_imlSmallIcons.Remove( i ); if( _taccess( sFolderPath, 0 ) == -1 ) return TRUE; SCStringVector::iterator itExt = m_Properties.m_vsExt.begin(); CSCADString sPath; struct _tfinddata_t fd; int nLargeIconInd = 0; int nSmallIconInd = 0; for( ; itExt != m_Properties.m_vsExt.end(); ++itExt ) { sPath = m_sFolderPath + _T("\\") + *itExt; intptr_t hFindHandle = _tfindfirst( sPath, &fd ); if( hFindHandle == -1 ) continue; AddFileTypeIcons(fd, nLargeIconInd, nSmallIconInd); do { AddFileItem(fd, nLargeIconInd, nSmallIconInd, *itExt); } while( _tfindnext( hFindHandle, &fd ) != -1 ); _findclose( hFindHandle ); } SortItems( m_flciColumns[m_nCurColumn].m_fnCmp, m_bSortAscending ); m_nImageBalance = m_nItemCount; SetRedrawItemPos( 0, true ); if( AfxGetMainWnd() ) { CSCADViewerStatBar &theStatusBar = static_cast<CScadViewerFrame*>(AfxGetMainWnd())->GetStatusBar(); theStatusBar.SetFileCount( m_nItemCount ); } UpdateFileCount(); return TRUE; }
void CVirtualFS::findFiles(const string &path, const string &extension, FindResult &fr){ S32 i; #ifdef _WIN32 struct _finddata_t fileinfo; #else struct dirent **entlist, *ent; #endif CollectionList::iterator col; for(col = fileCollections.begin() ; col != fileCollections.end() ; col++){ if(col->col_type == CFileCollection::QuakePAK){ } else if(col->col_type == CFileCollection::NativeCollection){ string fullPath = path; {S32 i=0; while((i = fullPath.find('\\', i)) != string::npos){ fullPath.replace(i, 1, "/"); }} Unz_GetStringForDir((unzFile*)col->zh, fullPath, extension, fr); } else if(col->col_type == CFileCollection::Directory){ string fullPath = fixFileName(path); i = fullPath.find(col->mMountPoint, 0); if(i != 0){ return; } fullPath.replace(0, col->mMountPoint.size(), ""); if(fullPath[0] == '/') fullPath.replace(0, 1, ""); fullPath = col->colPath + fullPath; #ifdef _WIN32 fullPath += "*." + extension; {S32 i=0; while((i = fullPath.find('/', i)) != string::npos){ fullPath.replace(i, 1, "\\"); }} S32 hd; hd = _findfirst(fullPath.c_str(), &fileinfo); if(hd != -1){ do { fr.push_back(CFile(path + fileinfo.name)); } while (_findnext(hd, &fileinfo) != -1); _findclose(hd); } #else S32 numfiles = scandir(fullPath.c_str(), &entlist, NULL, NULL); for(S32 i = 0 ; i < numfiles ; i++){ ent = entlist[i]; // Skip hidden if(ent->d_name[0]=='.')continue; // Keep requested files if(strncmp(extension.c_str(), ent->d_name + strlen(ent->d_name) - extension.length(), extension.length()))continue; fr.push_back(CFile(path + ent->d_name)); } #endif } } }
void CFileCollection::readFile(CFile &file){ unz_file_info info; U32 size; string name; switch(col_type){ case NativeCollection: name = fixSlashes(file.getName()); if(name[0] == '/') name.erase(name.begin()); if (unzLocateFile(zh, name.c_str(), 2) == UNZ_OK){ if (unzOpenCurrentFile(zh) == UNZ_OK){ if (unzGetCurrentFileInfo(zh, &info, NULL, 0, NULL, 0, NULL, 0)!= UNZ_OK) return; size = info.uncompressed_size; file.setSize(size); if((U32)unzReadCurrentFile(zh, file.getData(), size) != size){ unzCloseCurrentFile(zh); file.freeData(); return; } unzCloseCurrentFile(zh); return; } } else { string fname = name + "/"; if (unzLocateFile(zh, fname.c_str(), 2) == UNZ_OK){ CVirtualFS::FindResult fr; Unz_GetStringForDir((unzFile*)zh, fname, "", fr); string data; CVirtualFS::FindResult::iterator i; for(i = fr.begin();i != fr.end();i++){ data += (*i).getName(); data += "\n"; } data += "\0"; file.setSize(data.size()); memcpy(file.getData(), data.c_str(), data.size()); file.setIsDirectory(true); return; } } break; case Directory: S32 i = 0; FILE *fp = 0; U32 size; string fullName = file.getName(); i = fullName.find(mMountPoint, 0); if(i == string::npos){ return; } fullName.replace(i, mMountPoint.size(), ""); if(fullName[0] == '/') fullName.replace(0, 1, ""); fullName = colPath + fullName; #ifdef _WIN32 struct _finddata_t fileinfo; string pattern = fullName + "/*.*"; S32 hd = _findfirst(pattern.c_str(), &fileinfo); if(hd != -1){ // It is a directory string data(""); do { data += fullName + "/" + fileinfo.name + "\n"; } while (_findnext(hd, &fileinfo) != -1); data += "\0"; file.setSize(data.size()); memcpy(file.getData(), data.c_str(), data.size()); file.setIsDirectory(true); _findclose(hd); return; } #else //assert(0 && "NOT IMPLEMENTED DIRECTORY CHECK"); DIR *dirp; struct dirent *dp; dirp = opendir(fullName.c_str()); if(dirp){ string data(""); while( (dp = readdir(dirp)) != NULL ){ if(*dp->d_name == '.') continue; data += fullName + "/" + dp->d_name + "\n"; } data += "\0"; file.setSize(data.size()); memcpy(file.getData(), data.c_str(), data.size()); file.setIsDirectory(true); closedir(dirp); return; } #endif #ifdef _WIN32 while((i = fullName.find('/', i)) != string::npos){ fullName.replace(i, 1, "\\"); } #endif if (!fp) fp = fopen(fullName.c_str(), "rb"); if (fp) { fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); file.setSize(size); if (file.getData()) fread(file.getData(), 1, size, fp); fclose(fp); return; } } }
void findFiles(const std::string& pattern, bool recursives, bool dirs, std::vector<std::string>& simpleList) { intptr_t lHandle, res; struct _finddata_t tagData; size_t pos1 = pattern.rfind('/'); size_t pos2 = pattern.rfind('\\'); if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2))) pos1 = pos2; std::string directory; if (pos1 != pattern.npos) directory = pattern.substr(0, pos1 + 1); lHandle = _findfirst(pattern.c_str(), &tagData); res = 0; while (lHandle != -1 && res != -1) { if (dirs && ((tagData.attrib & _A_SUBDIR) != 0) && !is_reserved_dir(tagData.name)) { simpleList.push_back(directory + tagData.name); } if ((tagData.attrib & _A_SUBDIR) == 0) { simpleList.push_back(directory + tagData.name); } res = _findnext(lHandle, &tagData); } if (lHandle != -1) _findclose(lHandle); if (recursives) { std::string base_dir = directory; base_dir.erase(base_dir.length() - 1); base_dir.append("/*"); std::string mask("/"); if (pos1 != pattern.npos) mask.append(pattern.substr(pos1 + 1)); else mask.append(pattern); lHandle = _findfirst(base_dir.c_str(), &tagData); res = 0; while (lHandle != -1 && res != -1) { if ((tagData.attrib & _A_SUBDIR)) { base_dir = directory; base_dir.append(tagData.name).append(mask); findFiles(base_dir, recursives, dirs, simpleList); } res = _findnext(lHandle, &tagData); } if (lHandle != -1) _findclose(lHandle); } }
bool COptions::LoadLevels( std::string dynamicDataFolder, std::string pgmFolder ) { long FindHandle; _finddata_t FindData; #ifndef WIN32 // initialise OUR data structure FindData.name = NULL; FindData.suffix = NULL; #endif //------------------------------------------- // Set the path where the level files are stored // (in the program files folder) //------------------------------------------- std::string levelFilePath_pgmFolder; levelFilePath_pgmFolder = pgmFolder; if (pgmFolder.length() >= 1) { char delim = pgmFolder.c_str()[pgmFolder.length()-1]; if (delim != '\\' && delim != '/') #ifdef WIN32 levelFilePath_pgmFolder.append("\\"); #else levelFilePath_pgmFolder.append("/"); #endif } #ifdef WIN32 levelFilePath_pgmFolder.append( "Levels\\" ); #else levelFilePath_pgmFolder.append( "Levels/" ); #endif std::string levelFilePath_pgmFolderMask; levelFilePath_pgmFolderMask = levelFilePath_pgmFolder; levelFilePath_pgmFolderMask.append( "*.TXT" ); //------------------------------------------- // Determine number of level files available // (in the program files folder) //------------------------------------------- theLog.WriteLine( "Options => Loading level files '%s'.", levelFilePath_pgmFolderMask.c_str() ); FindHandle = _findfirst( levelFilePath_pgmFolderMask.c_str(), &FindData ); if (FindHandle != -1) { do { std::string fileNameWithoutPath( FindData.name ); std::string fileNameWithPath( levelFilePath_pgmFolder ); fileNameWithPath.append( FindData.name ); // Create a new CLevel element and add it to the level container m_Levels.push_back( CLevel( fileNameWithPath, fileNameWithoutPath ) ); } while (_findnext(FindHandle, &FindData) != -1); } _findclose(FindHandle); // If a dynamic folder is set, load level files from there, too if ( dynamicDataFolder != "" ) { //------------------------------------------- // Set the path where the level files are stored // (in the user's application data folder) //------------------------------------------- std::string levelFilePath_dynamicDataFolder; levelFilePath_dynamicDataFolder = dynamicDataFolder; #ifdef WIN32 levelFilePath_dynamicDataFolder.append( "Levels\\" ); #else levelFilePath_dynamicDataFolder.append( "Levels/" ); #endif std::string levelFilePath_dynamicDataFolderMask; levelFilePath_dynamicDataFolderMask = levelFilePath_dynamicDataFolder; levelFilePath_dynamicDataFolderMask.append( "*.TXT" ); //------------------------------------------- // Determine number of level files available // (in the dynamic data folder) //------------------------------------------- theLog.WriteLine( "Options => Loading level files '%s'.", levelFilePath_dynamicDataFolderMask.c_str() ); FindHandle = _findfirst( levelFilePath_dynamicDataFolderMask.c_str(), &FindData ); if (FindHandle != -1) { do { std::string fileNameWithoutPath( FindData.name ); std::string fileNameWithPath( levelFilePath_dynamicDataFolder ); fileNameWithPath.append( FindData.name ); // Create a new CLevel element and add it to the level container m_Levels.push_back( CLevel( fileNameWithPath, fileNameWithoutPath ) ); } while (_findnext(FindHandle, &FindData) != -1); } _findclose(FindHandle); } //--------------------- // Check for a problem //--------------------- // If there is no level if (m_Levels.size() == 0) { // Log failure theLog.WriteLine ("Options => !!! There should be at least 1 level."); return false; } // If the level number we read in the cfg file is invalid compared to the number of existing levels if (m_Level >= (int)m_Levels.size()) // #3078839 { // Select the first level m_Level = 0; } //------------------------------------------------------ // Load all the level files detected earlier //------------------------------------------------------ bool ErrorOccurred = false; for( unsigned int CurrentLevel = 0; CurrentLevel < m_Levels.size(); CurrentLevel++ ) { //theLog.WriteLine ("Options => Loading level file %s...", levelFileNames_full.at(CurrentLevel).c_str() ); if ( !m_Levels.at( CurrentLevel ).LoadFromFile() ) { ErrorOccurred = true; break; } } // If we had to stop then there is a problem. if (ErrorOccurred) return false; // Everything went right return true; }
void CLogI::getOldFiles( string path, vector<string>& files, time_t today, int nDayOld ) { //文件句柄 intptr_t hFile = 0; //文件信息 struct _finddata_t fileinfo; time_t tcomp; tcomp = nDayOld * 24 * 60 * 60; WLock(m_muMap) { queryMap.clear(); string p; if ((hFile = _findfirst(p.assign(path).append("/*").c_str(),&fileinfo)) != -1) { do { //如果是目录,迭代之 //如果不是,加入列表 if ((fileinfo.attrib & _A_SUBDIR)) { // if (strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0) // getFiles( p.assign(path).append("/").append(fileinfo.name), files ); } else { time_t tDiff = today - fileinfo.time_write; //struct tm Diff; //_localtime64_s(&Diff, &tDiff); string strfileName = ""; strfileName = p.assign(path).append("/").append(fileinfo.name); if (tDiff > tcomp) { files.push_back( strfileName ); } else { long long dateKey = 0; string strDate; strDate = fileinfo.name; strDate.replace(0, sizeof(LOG_DB_FILE)-1, "" ); sscanf_s(strDate.c_str(), "%lld", &dateKey); if (dateKey > 0) { //map <int, string>::iterator qu_Iter = queryMap.find(dateKey); //if (qu_Iter) { queryMap.insert(IntStr_Pair(dateKey, strfileName)); } } } } } while (_findnext( hFile, &fileinfo ) == 0); _findclose(hFile); } } }
// End search. void EndFileSearch(void) { if(nHandle > -1) _findclose(nHandle); }
int main(int ac, char **av) { #ifdef _WIN32 intptr_t dir; struct _finddata_t c_file; #else struct dirent *dp; DIR *dir; #endif int failed = 0; int completed = 0; enum asn1p_flags parser_flags = A1P_NOFLAGS; enum asn1f_flags fixer_flags = A1F_NOFLAGS; const char *filename; size_t len; int ret; /* * Just in case when one decides that some flags better be * enabled during `ASN1_FIXER_FLAGS=1 make check` or some * similar usage. */ if(getenv("ASN1_PARSER_FLAGS")) parser_flags = atoi(getenv("ASN1_PARSER_FLAGS")); if(getenv("ASN1_FIXER_FLAGS")) fixer_flags = atoi(getenv("ASN1_FIXER_FLAGS")); /* * Go into a directory with tests. */ if(ac <= 1) { fprintf(stderr, "Testing in ./tests...\n"); ret = chdir("../tests"); assert(ret == 0); #ifdef _WIN32 dir = _findfirst("*.asn1", &c_file); assert(dir != -1L); #else dir = opendir("."); assert(dir); #endif /* _WIN32 */ } else { dir = 0; } /* * Scan every *.asn1 file and try to parse and fix it. */ if(dir) { #ifdef _WIN32 do { filename = c_file.name; #else while((dp = readdir(dir))) { filename = dp->d_name; #endif /* _WIN32 */ len = strlen(filename); if(len <= 5 || strcmp(filename + len - 5, ".asn1")) continue; ret = check(filename, parser_flags, fixer_flags); if(ret) { fprintf(stderr, "FAILED: %s\n", filename); failed++; } completed++; #ifdef _WIN32 } while(_findnext(dir, &c_file) == 0); _findclose(dir); #else } closedir(dir); #endif /* _WIN32 */ fprintf(stderr, "Tests COMPLETED: %d\n" "Tests FAILED: %d\n" , completed, failed ); } else {
BOOL PathNameEx::RemoveRecursively(const String_256& rPath) { PORTNOTETRACE("other","PathNameEx::RemoveRecursively - do nothing"); #ifndef EXCLUDE_FROM_XARALX String_256 strFilename(rPath); strFilename.toLower(); // See if the path points to a file (the easy case) or a directory if (strFilename[strFilename.Length() - 1] == chPathSep) { strFilename.Remove(strFilename.Length() - 1, 1); goto DIRECTORY; } struct _stat fileData; if (_stat((TCHAR*) strFilename, &fileData)) { if (errno == ENOENT) { ERROR3("Filename or path not found"); } else { ERROR3("_stat() failed with an unknown error"); } return FALSE; } if (fileData.st_mode & _S_IFDIR) // directory { DIRECTORY: // Make sure the directory is not the current one TCHAR tchbuff[_MAX_PATH]; if (_getcwd(tchbuff, _MAX_PATH) == NULL) { ERROR3("Can't get working directory"); return FALSE; } if (strstr(_strlwr(tchbuff), (TCHAR*) strFilename)) { // change to upper dir (we should never attempt to delete the root directory!) PathName path(strFilename); if (_chdir((TCHAR*) String_256(path.GetLocation(FALSE)))) { ERROR3("Can't change directory"); return FALSE; } } // Try to remove it in the hope that it's empty if (_rmdir((TCHAR*) strFilename) == -1) { if (errno == ENOTEMPTY || errno == EACCES) { _finddata_t findData; String_256 strSearchPattern(strFilename); strSearchPattern += chPathSep; strSearchPattern += _T("*"); // add wildcard INT32 hSearch = _findfirst(strSearchPattern, &findData); if (hSearch == -1) return FALSE; do { if (!(strcmp(findData.name, _T(".")) && strcmp(findData.name, _T("..")))) continue; // skip this directory (.) or its parent (..) String_256 strFoundFile(strFilename); strFoundFile += chPathSep; strFoundFile += findData.name; RemoveRecursively(strFoundFile); } while (_findnext(hSearch, &findData) == 0); _findclose(hSearch); return (_rmdir((TCHAR*) strFilename) != -1); } else { return FALSE; // probably invalid path } } else return TRUE; // succedded } else if (fileData.st_mode & _S_IFREG) // file return (remove((TCHAR*) strFilename) != -1); else #endif return FALSE; }
void CFolderListCtrl::RefreshFileList() { std::vector<CFLCItemData *>arrListCache(m_nItemCount); int i; for (i=0;i<m_nItemCount;i++) { arrListCache[i] = reinterpret_cast<CFLCItemData *>(GetItemData(i)); arrListCache[i]->m_bFoundOnRefresh = false; } SCStringVector::iterator itExt = m_Properties.m_vsExt.begin(); CSCADString sPath; struct _tfinddata_t fd; int nLargeIconInd = 0; int nSmallIconInd = 0; int nItemCount = m_nItemCount; for( ; itExt != m_Properties.m_vsExt.end(); ++itExt ) { sPath = m_sFolderPath + _T("\\") + *itExt; intptr_t hFindHandle = _tfindfirst( sPath, &fd ); if( hFindHandle == -1 ) continue; AddFileTypeIcons(fd, nLargeIconInd, nSmallIconInd); do { bool bFileFound = false; CSCADString sFileName; if( m_sFolderPath.GetLength() && ( m_sFolderPath[m_sFolderPath.GetLength()-1] == _T('\\') || m_sFolderPath[m_sFolderPath.GetLength()-1] == _T('/') ) ) sFileName = m_sFolderPath+ fd.name; else sFileName = m_sFolderPath + ( _T("\\") ) + fd.name; for (int k=0; k<nItemCount;k++) { if (arrListCache[k]->m_sFilePath == sFileName) { bFileFound = true; arrListCache[k]->m_bFoundOnRefresh = true; if (fd.time_write != arrListCache[k]->m_tModified) { arrListCache[k]->m_bProcessed = false; if (m_strSelectedPath.CompareNoCase(arrListCache[k]->m_sFilePath)==0) { CSCAD3DMdlSettings::Get3DS()->SetViewFilePath( arrListCache[k]->m_sFilePath, arrListCache[k]->m_sExt ); } break; } } } if (!bFileFound) { AddFileItem(fd, nLargeIconInd, nSmallIconInd,*itExt); } } while( _tfindnext( hFindHandle, &fd ) != -1 ); _findclose( hFindHandle ); } m_nImageBalance = 0; for (i=0;i<m_nItemCount;i++) { CFLCItemData *pData = reinterpret_cast<CFLCItemData *>(GetItemData(i)); if (!pData->m_bFoundOnRefresh) { delete pData; CListCtrl::DeleteItem(i); m_nItemCount--; } else { if (!pData->m_bProcessed) m_nImageBalance++; } } SortItems( m_flciColumns[m_nCurColumn].m_fnCmp, m_bSortAscending ); ASSERT(m_nItemCount == GetItemCount()); UpdateFileCount(); SetRedrawItemPos( 0, true ); }
/* Main program */ int main (int argc, char **argv) { char *opt, *needle = NULL; int ret = 0; WCHAR wszMessage[4096]; char oemMessage[4096]; int invert_search = 0; /* flag to invert the search */ int count_lines = 0; /* flag to whether/not count lines */ int number_output = 0; /* flag to print line numbers */ int ignore_case = 0; /* flag to be case insensitive */ FILE *pfile; /* file pointer */ int hfind; /* search handle */ struct _finddata_t finddata; /* _findfirst, filenext block */ /* Scan the command line */ while ((--argc) && (needle == NULL)) { if (*(opt = *++argv) == '/') { switch (opt[1]) { case 'c': case 'C': /* Count */ count_lines = 1; break; case 'i': case 'I': /* Ignore */ ignore_case = 1; break; case 'n': case 'N': /* Number */ number_output = 1; break; case 'v': case 'V': /* Not with */ invert_search = 1; break; default: usage (); exit (2); /* syntax error .. return error 2 */ break; } } else { /* Get the string */ if (needle == NULL) { /* Assign the string to find */ needle = *argv; } } } /* Check for search string */ if (needle == NULL) { /* No string? */ usage (); exit (1); } /* Scan the files for the string */ if (argc == 0) { ret = find_str (needle, stdin, invert_search, count_lines, number_output, ignore_case); } while (--argc >= 0) { hfind = _findfirst (*++argv, &finddata); if (hfind < 0) { /* We were not able to find a file. Display a message and set the exit status. */ LoadStringW (GetModuleHandleW (NULL), IDS_NO_SUCH_FILE, wszMessage, sizeof(wszMessage) / sizeof(wszMessage[0])); CharToOemW (wszMessage, oemMessage); fprintf (stderr, oemMessage, *argv); } else { /* repeat find next file to match the filemask */ do { /* We have found a file, so try to open it */ if ((pfile = fopen (finddata.name, "r")) != NULL) { printf ("---------------- %s\n", finddata.name); ret = find_str (needle, pfile, invert_search, count_lines, number_output, ignore_case); fclose (pfile); } else { LoadStringW (GetModuleHandleW (NULL), IDS_CANNOT_OPEN, wszMessage, sizeof(wszMessage) / sizeof(wszMessage[0])); CharToOemW (wszMessage, oemMessage); fprintf (stderr, oemMessage, finddata.name); } } while (_findnext(hfind, &finddata) > 0); } _findclose(hfind); } /* for each argv */ /* RETURN: If the string was found at least once, returns 0. * If the string was not found at all, returns 1. * (Note that find_str.c returns the exact opposite values.) */ exit ( (ret ? 0 : 1) ); }
// Description: // // Arguments: // // Return: // bool CVisualLog::OpenLogs() { m_sFormat = m_pCVVisualLogImageFormat->GetString(); m_eFormat = GetFormatType( m_sFormat ); m_sLogFolder = m_pCVVisualLogFolder->GetString(); int iLogFolderLen = m_sLogFolder.length(); // Check we have good params to use if ( m_eFormat == EVLF_NONE || iLogFolderLen == 0 ) { GameWarning( "[VisualLog] File format or log folder value invalid" ); return false; } // Create base directory if necessary CryCreateDirectory( m_sLogFolder ); // Figure out next number in sequence m_sLogFolderName/m_sLogFolderNameXXXX, where XXXX is 0000, 0001, etc. int iSeqNum = 0; __finddata64_t fd; intptr_t handle = _findfirst64( PathUtil::Make( m_sLogFolder , "*.*" ), &fd ); if ( handle != -1 ) { do { // Is it a directory with our base name as a prefix? if ( fd.attrib & _A_SUBDIR && fd.name[0]!='.' && !_strnicmp( m_sLogFolder, fd.name, iLogFolderLen ) ) { iSeqNum = max( iSeqNum, atoi( fd.name + iLogFolderLen ) + 1 ); } } while (0 == _findnext64 (handle, &fd)); _findclose(handle); } // Now create directory char sLogPath[256]; _snprintf( sLogPath, sizeof(sLogPath), "%s\\%s%04d", m_sLogFolder.c_str(), m_sLogFolder.c_str(), iSeqNum ); if ( !CryCreateDirectory( sLogPath ) ) { GameWarning( "[VisualLog] Unable to create directory for log files: %s", sLogPath ); return false; } m_sLogPath = sLogPath; m_iLogFolderNum = iSeqNum; char sLogFileName[256]; _snprintf( sLogFileName, sizeof(sLogFileName), "%s\\%s%04d.log", m_sLogPath.c_str(), m_sLogFolder.c_str(), m_iLogFolderNum ); char sLogParamsFileName[256]; _snprintf( sLogParamsFileName, sizeof(sLogParamsFileName), "%s\\%s%04d_params.log", m_sLogPath.c_str(), m_sLogFolder.c_str(), m_iLogFolderNum ); // Open Log Files m_fLogFile = fxopen(sLogFileName, "w"); m_fLogParamsFile = fxopen(sLogParamsFileName, "w"); if ( !m_fLogFile || !m_fLogParamsFile ) { GameWarning( "[VisualLog] Unable to open log files [%s] [%s]", sLogFileName, sLogParamsFileName ); CloseLogs(); return false; } WriteFileHeaders( sLogFileName, sLogParamsFileName ); return true; }
int Dir_Close(Dir* dir) { _findclose(dir->handle); PAL_Free(dir); return 0; }
BOOL DLLCALL fexistcase(char *path) { #if defined(_WIN32) char* fname; long handle; struct _finddata_t f; if(access(path,0)==-1 && !strchr(path,'*') && !strchr(path,'?')) return(FALSE); if((handle=_findfirst((char*)path,&f))==-1) return(FALSE); _findclose(handle); if(f.attrib&_A_SUBDIR) return(FALSE); fname=getfname(path); /* Find filename in path */ strcpy(fname,f.name); /* Correct filename */ return(TRUE); #else /* Unix or OS/2 */ char globme[MAX_PATH*4+1]; char fname[MAX_PATH+1]; char tmp[5]; char *p; int i; glob_t glb; if(path[0]==0) /* work around glibc bug 574274 */ return FALSE; if(!strchr(path,'*') && !strchr(path,'?') && fnameexist(path)) return(TRUE); SAFECOPY(globme,path); p=getfname(globme); SAFECOPY(fname,p); *p=0; for(i=0;fname[i];i++) { if(isalpha(fname[i])) sprintf(tmp,"[%c%c]",toupper(fname[i]),tolower(fname[i])); else sprintf(tmp,"%c",fname[i]); strncat(globme,tmp,MAX_PATH*4); } #if 0 if(strcspn(path,"?*")!=strlen(path)) { sprintf(path,"%.*s",MAX_PATH,globme); return(fexist(path)); } #endif if(glob(globme,GLOB_MARK,NULL,&glb) != 0) return(FALSE); if(glb.gl_pathc>0) { for(i=0;i<glb.gl_pathc;i++) { if(*lastchar(glb.gl_pathv[i]) != '/') break; } if(i<glb.gl_pathc) { sprintf(path,"%.*s",MAX_PATH,glb.gl_pathv[i]); globfree(&glb); return TRUE; } } globfree(&glb); return FALSE; #endif }
//Removes PCA space directories void CPCAUtils::RemoveDirectories() { //aux vars long l; //Projections chdir(ProjectionsDir); #ifndef ENCARA2INLINUX struct _finddata_t fi; l=(long)_findfirst("*", &fi); if (l!=-1) { do { if (strcmp(fi.name,".") && strcmp(fi.name,"..") && strcmp(fi.name,"CVS")) { remove(fi.name); } } while (_findnext(l, &fi)==0); _findclose(l); } #else glob_t fi; int i; //Indica el número de posiciones que aloja fi.gl_offs=MAXFILES; glob("*", GLOB_DOOFFS, NULL, &fi); fi.gl_offs = 2; for (i=0;i<(int)fi.gl_pathc;i++) { //Borra todos if (strcmp(fi.gl_pathv[i],".") && strcmp(fi.gl_pathv[i],"..") && strcmp(fi.gl_pathv[i],"CVS")) { remove(fi.gl_pathv[i]); } } globfree(&fi); #endif //Eigenobjects chdir(EigenobjectsDir); #ifndef ENCARA2INLINUX l=(long)_findfirst("*", &fi); if (l!=-1) { do { if (strcmp(fi.name,".") && strcmp(fi.name,"..") && strcmp(fi.name,"CVS")) { remove(fi.name); } } while (_findnext(l, &fi)==0); _findclose(l); } #else //Indica el número de posiciones que aloja fi.gl_offs=MAXFILES; glob("*", GLOB_DOOFFS, NULL, &fi); //Borra for (i=0;i<(int)fi.gl_pathc;i++) { if (strcmp(fi.gl_pathv[i],".") && strcmp(fi.gl_pathv[i],"..") && strcmp(fi.gl_pathv[i],"CVS")) { remove(fi.gl_pathv[i]); } } globfree(&fi); #endif }
void InitializeDialog(HWND hDlg) { struct _finddata_t c_file; long hFile; FILE *fhan; int idx; retrieve_filter_list(false); SendDlgItemMessage(hDlg,IDC_VERSION, WM_SETTEXT, 0, (LPARAM)setupstring); SendDlgItemMessage(hDlg,IDC_GFXDRIVER,CB_ADDSTRING,0,(LPARAM)"DirectDraw 5"); SendDlgItemMessage(hDlg,IDC_GFXDRIVER,CB_ADDSTRING,0,(LPARAM)"Direct3D 9"); SendDlgItemMessage(hDlg,IDC_COMBO1,CB_RESETCONTENT,0,0); SendDlgItemMessage(hDlg,IDC_COMBO1,CB_ADDSTRING,0,(LPARAM)"Default DirectSound Device"); SendDlgItemMessage(hDlg,IDC_COMBO1,CB_ADDSTRING,0,(LPARAM)"Default WaveOut Device"); SendDlgItemMessage(hDlg,IDC_COMBO1,CB_ADDSTRING,0,(LPARAM)"No Digital Sound"); SendDlgItemMessage(hDlg,IDC_COMBO1,CB_ADDSTRING,0,(LPARAM)"DirectSound (Hardware mixer)"); SendDlgItemMessage(hDlg,IDC_COMBO1,CB_SETTOPINDEX,0,0); SendDlgItemMessage(hDlg,IDC_COMBO1,CB_SETCURSEL,curdigi,0); SendDlgItemMessage(hDlg,IDC_COMBO2,CB_ADDSTRING,0,(LPARAM)"Default MCI Music Device"); SendDlgItemMessage(hDlg,IDC_COMBO2,CB_ADDSTRING,0,(LPARAM)"Disable music"); SendDlgItemMessage(hDlg,IDC_COMBO2,CB_ADDSTRING,0,(LPARAM)"Win32 MIDI Mapper"); SendDlgItemMessage(hDlg,IDC_COMBO2,CB_SETTOPINDEX,0,0); SendDlgItemMessage(hDlg,IDC_COMBO2,CB_SETCURSEL,curmidi,0); SendDlgItemMessage(hDlg,IDC_COMBO3,CB_ADDSTRING,0,(LPARAM)"Game Default"); SendDlgItemMessage(hDlg,IDC_COMBO3,CB_SETCURSEL,0,0); idx = 1; char translationFindSpec[255]; sprintf(translationFindSpec, "%s\\*.tra", curdatadir); // Find and add all translations in folder if ((hFile = _findfirst(translationFindSpec, &c_file )) != -1L ) { do { if (c_file.name[strlen(c_file.name)-4] == '.') { // it actually returns *.tra* so make sure it's a .TRA file, // then add to our list c_file.name[0] = toupper (c_file.name[0]); c_file.name[strlen(c_file.name)-4] = 0; int needToSet = 0; // if this is the translation we're using, set it if (stricmp (curtranslation, c_file.name) == 0) needToSet = 1; strcat (c_file.name, " translation"); SendDlgItemMessage(hDlg,IDC_COMBO3,CB_ADDSTRING,0,(LPARAM)c_file.name); if (needToSet) SendDlgItemMessage (hDlg, IDC_COMBO3, CB_SETCURSEL, idx, 0); idx++; } } while( _findnext( hFile, &c_file ) == 0 ); _findclose( hFile ); } SendDlgItemMessage(hDlg,IDC_COMBO4,CB_ADDSTRING,0,(LPARAM)"10 MB"); SendDlgItemMessage(hDlg,IDC_COMBO4,CB_ADDSTRING,0,(LPARAM)"20 MB (default)"); SendDlgItemMessage(hDlg,IDC_COMBO4,CB_ADDSTRING,0,(LPARAM)"50 MB"); SendDlgItemMessage(hDlg,IDC_COMBO4,CB_ADDSTRING,0,(LPARAM)"100 MB"); idx = 0; if (curmaxcache >= 100*1024) idx = 3; else if (curmaxcache >= 50*1024) idx = 2; else if (curmaxcache >= 20*1024) idx = 1; SendDlgItemMessage(hDlg,IDC_COMBO4,CB_SETCURSEL,idx,0); SendDlgItemMessage(hDlg,IDC_REPLAYBOX,CB_ADDSTRING,0,(LPARAM)"Don't run a replay"); SendDlgItemMessage(hDlg,IDC_REPLAYBOX,CB_SETCURSEL,0,0); idx = 1; // Find and add all replays in folder if ((hFile = _findfirst( "*.agr", &c_file )) != -1L ) { do { if (c_file.name[strlen(c_file.name)-4] == '.') { // it actually returns *.agr* so make sure it's a .AGR file, // then add to our list char listentry[300] = "(unknown replay)"; get_replay_name (c_file.name, listentry); strcat (listentry, " (File: "); strcat (listentry, c_file.name); strcat (listentry, ")"); int needToSet = 0; // if this is the translation we're using, set it if (stricmp (curreplay, c_file.name) == 0) needToSet = 1; SendDlgItemMessage(hDlg,IDC_REPLAYBOX,CB_ADDSTRING,0,(LPARAM)listentry); if (needToSet) SendDlgItemMessage (hDlg, IDC_REPLAYBOX, CB_SETCURSEL, idx, 0); idx++; } } while( _findnext( hFile, &c_file ) == 0 ); _findclose( hFile ); } populate_drop_down_with_filters(hDlg); if (stricmp(curGfxDriver, "D3D9") == 0) SendDlgItemMessage(hDlg, IDC_GFXDRIVER, CB_SETCURSEL, 1, 0); else SendDlgItemMessage(hDlg, IDC_GFXDRIVER, CB_SETCURSEL, 0, 0); update_gfx_filter_box_enabled(hDlg); if (windowed > 0) SendDlgItemMessage(hDlg,IDC_WINDOWED,BM_SETCHECK,BST_CHECKED,0); if (refresh > 0) SendDlgItemMessage(hDlg,IDC_REFRESH,BM_SETCHECK,BST_CHECKED,0); if (antialias > 0) SendDlgItemMessage(hDlg,IDC_ANTIALIAS,BM_SETCHECK,BST_CHECKED,0); if (curusespeech > 0) SendDlgItemMessage(hDlg,IDC_SPEECHPACK,BM_SETCHECK,BST_CHECKED,0); if (sideBorders > 0) SendDlgItemMessage(hDlg, IDC_SIDEBORDERS, BM_SETCHECK, BST_CHECKED, 0); if (useletterbox > 0) SendDlgItemMessage(hDlg, IDC_LETTERBOX,BM_SETCHECK,BST_CHECKED,0); // If the game is 320x240, don't let them un-tick it if (mustBeLetterbox) EnableWindow (GetDlgItem (hDlg, IDC_LETTERBOX), FALSE); // If it's 800x600, hide the letterbox option if (defaultRes >= 5) ShowWindow (GetDlgItem (hDlg, IDC_LETTERBOX), SW_HIDE); // If the game isn't 32-bit, disable it if (gameColDep < 32) EnableWindow (GetDlgItem (hDlg, IDC_REDUCESPR), FALSE); else if (reduce32to16 > 0) SendDlgItemMessage(hDlg, IDC_REDUCESPR, BM_SETCHECK, BST_CHECKED,0); // if no speech pack, disable the checkbox fhan = fopen("speech.vox", "rb"); if (fhan == NULL) EnableWindow (GetDlgItem (hDlg, IDC_SPEECHPACK), FALSE); else fclose(fhan); if (INIreadint("disabled", "speechvox", 0) == 1) EnableWindow (GetDlgItem (hDlg, IDC_SPEECHPACK), FALSE); if (INIreadint("disabled", "16bit", 0) == 1) EnableWindow (GetDlgItem (hDlg, IDC_REDUCESPR), FALSE); if (INIreadint("disabled", "filters", 0) == 1) EnableWindow (GetDlgItem(hDlg, IDC_GFXFILTER), FALSE); RECT winsize; GetWindowRect (hDlg, &winsize); wwidth = winsize.right - winsize.left; wheight = winsize.bottom - winsize.top; MoveWindow (hDlg, winsize.left, winsize.top, wwidth, wheight-175, TRUE); update_resolution_texts (hDlg); SendMessage(hDlg, WM_SETTEXT, NULL, (LPARAM)gameNameForTitleBar); SendMessage(allegro_wnd, WM_SETTEXT, NULL, (LPARAM)gameNameForTitleBar); }
// LoadDataset: Loads dataset from disk to memory ClassifiedImageDataset* CPCAUtils::LoadClassifiedDataset(char *directory) { int c,j,NumClases; unsigned int TotalImagenes=0; bool bojpg=false; ClassifiedImageDataset *BaseDeCaras=(ClassifiedImageDataset*)new char[sizeof(ClassifiedImageDataset)]; chdir(directory); // Primero vemos cuantas clases tenemos y el total de frames... NumClases=0; bool boOneClassHasNoImages=false; #ifndef ENCARA2INLINUX struct _finddata_t fi,ff; long l,m; l=(long)_findfirst("*", &fi); if (l!=-1) { do { //Si tiene atributo de subdirectorio y no es . o .. o CVS //if (strcmp(fi.name,".") && strcmp(fi.name,"..") && strcmp(fi.name,"CVS") && (fi.attrib==_A_SUBDIR)) if (strcmp(fi.name,".") && strcmp(fi.name,"..") && strcmp(fi.name,"CVS") && (fi.attrib==_A_SUBDIR)) { NumClases++; chdir(fi.name); //Check first for Ipl m=(long)_findfirst("*.Ipl", &ff); //If not checks for jpg if (m==-1) { m=(long)_findfirst("*.jpg", &ff); bojpg=true; } if (m!=-1) { do { TotalImagenes++; } while (_findnext(m, &ff)==0); } else boOneClassHasNoImages=true;//There are no samples for one class _findclose(m); _chdir(".."); } } while (_findnext(l, &fi)==0); _findclose(l); } #else//Falta terminarlo int i; glob_t fi,ff; //Indica el número de posiciones que aloja fi.gl_offs=MAXFILES; ff.gl_offs=MAXFILES; glob("*", GLOB_DOOFFS, NULL, &fi); for (i=0;i<(int)fi.gl_pathc;i++) { //Asume que todos son directorios (ojo) if (strcmp(fi.gl_pathv[i],".") && strcmp(fi.gl_pathv[i],"..") && strcmp(fi.gl_pathv[i],"CVS")) { NumClases++; chdir(fi.gl_pathv[i]); glob("*.Ipl", GLOB_DOOFFS, NULL, &ff); if (ff.gl_pathc==0) { glob("*.jpg", GLOB_DOOFFS, NULL, &ff); bojpg=true; } if (ff.gl_pathc==0) TotalImagenes=ff.gl_pathc; else boOneClassHasNoImages=true;//There are no samples for one class chdir(".."); globfree(&ff); } } globfree(&fi); #endif //Si no hay imàgenes o clases if (NumClases<=0 || TotalImagenes<(unsigned int)NumClases || boOneClassHasNoImages) { delete [] BaseDeCaras; return NULL; } unsigned int *FramesPorClase=(unsigned int*)new unsigned char[NumClases*sizeof(unsigned int)]; IplImage** BC=(IplImage**) new unsigned char[TotalImagenes*sizeof(IplImage*)]; char** Identidad=(char**) new unsigned char[TotalImagenes*sizeof(char*)]; //Ahora tras saber lo que hay y cerar las estructuras, lee las imágenes c=0; unsigned int Frame=0; #ifndef ENCARA2INLINUX l=(long)_findfirst("*", &fi); if (l!=-1) { do { //if (strcmp(fi.name,".") && strcmp(fi.name,"..") && strcmp(fi.name,"CVS") && (fi.attrib==_A_SUBDIR)) if (strcmp(fi.name,".") && strcmp(fi.name,"..") && strcmp(fi.name,"CVS") && (fi.attrib==_A_SUBDIR)) { c++; _chdir(fi.name); j=0; //Check first for Ipl if (!bojpg) m=(long)_findfirst("*.Ipl", &ff); else m=(long)_findfirst("*.jpg", &ff); if (m!=-1) { do { j++; if (!bojpg) BC[Frame] = IplUtils.LoadIplImage(ff.name); #ifndef USES_OF else BC[Frame] = cvLoadImage(ff.name,0); //Fuerza cargar imagen grises #endif Identidad[Frame]=(char*)new unsigned char[sizeof(char)*ID_STRING_SIZE]; strcpy(Identidad[Frame],fi.name); Frame++; } while (_findnext(m, &ff)==0); } _findclose(m); _chdir(".."); FramesPorClase[c-1]=j; } } while (_findnext(l, &fi)==0); _findclose(l); } #else glob("*", GLOB_DOOFFS, NULL, &fi); for (i=0;i<(int)fi.gl_pathc;i++) { //Asume que todos son directorios (ojo) if (strcmp(fi.gl_pathv[i],".") && strcmp(fi.gl_pathv[i],"..") && strcmp(fi.gl_pathv[i],"CVS")) { c++; chdir(fi.gl_pathv[i]); j=0; if (!bojpg) glob("*.Ipl", GLOB_DOOFFS, NULL, &ff); else glob("*.jpg", GLOB_DOOFFS, NULL, &ff); for (j=0;j<(int)ff.gl_pathc;j++) { if (!bojpg) BC[Frame] = IplUtils.LoadIplImage(ff.gl_pathv[j]); #ifndef USES_OF else BC[Frame] = cvLoadImage(ff.gl_pathv[j],0); //Fuerza cargar imagen grises #endif Identidad[Frame]=(char*)new unsigned char[sizeof(char)*ID_STRING_SIZE]; strcpy(Identidad[Frame],fi.gl_pathv[j]); Frame++; } FramesPorClase[c-1]=ff.gl_pathc; chdir(".."); globfree(&ff); } } globfree(&fi); #endif BaseDeCaras->BC=BC; BaseDeCaras->FramesPerClass=FramesPorClase; BaseDeCaras->Label=Identidad; BaseDeCaras->NumClasses=NumClases; BaseDeCaras->TotalImages=TotalImagenes; BaseDeCaras->ImageSize=cvSize(BC[0]->width,BC[0]->height); return BaseDeCaras; }
bool AP_Win32App::initialize(void) { bool bSuccess = true; const char * szUserPrivateDirectory = getUserPrivateDirectory(); bool bVerified = s_createDirectoryIfNecessary(szUserPrivateDirectory); UT_return_val_if_fail (bVerified, false); // load the preferences. m_prefs = new AP_Win32Prefs(); UT_return_val_if_fail (m_prefs, false); m_prefs->fullInit(); // now that preferences are established, let the xap init m_pClipboard = new AP_Win32Clipboard(); UT_return_val_if_fail (m_pClipboard, false); m_pEMC = AP_GetEditMethods(); UT_return_val_if_fail (m_pEMC, false); m_pBindingSet = new AP_BindingSet(m_pEMC); UT_return_val_if_fail (m_pBindingSet, false); m_pMenuActionSet = AP_CreateMenuActionSet(); UT_return_val_if_fail (m_pMenuActionSet,false); m_pToolbarActionSet = AP_CreateToolbarActionSet(); UT_return_val_if_fail (m_pToolbarActionSet,false); ////////////////////////////////////////////////////////////////// // load the dialog and message box strings ////////////////////////////////////////////////////////////////// { // assume we will be using the builtin set (either as the main // set or as the fallback set). AP_BuiltinStringSet * pBuiltinStringSet = new AP_BuiltinStringSet(this,AP_PREF_DEFAULT_StringSet); UT_return_val_if_fail (pBuiltinStringSet, false); m_pStringSet = pBuiltinStringSet; // see if we should load an alternate set from the disk const char * szDirectory = NULL; const char * szStringSet = NULL; if ( (getPrefsValue(AP_PREF_KEY_StringSet,&szStringSet)) && (szStringSet) && (*szStringSet) && (g_ascii_strcasecmp(szStringSet,AP_PREF_DEFAULT_StringSet) != 0)) { getPrefsValueDirectory(true,AP_PREF_KEY_StringSetDirectory,&szDirectory); UT_return_val_if_fail ((szDirectory) && (*szDirectory), false); char * szPathname = (char *)UT_calloc(sizeof(char),strlen(szDirectory)+strlen(szStringSet)+100); UT_return_val_if_fail (szPathname, false); sprintf(szPathname,"%s%s%s.strings", szDirectory, ((szDirectory[strlen(szDirectory)-1]=='\\') ? "" : "\\"), szStringSet); AP_DiskStringSet * pDiskStringSet = new AP_DiskStringSet(this); UT_return_val_if_fail (pDiskStringSet, false); if (pDiskStringSet->loadStringsFromDisk(szPathname)) { pDiskStringSet->setFallbackStringSet(m_pStringSet); m_pStringSet = pDiskStringSet; UT_Language_updateLanguageNames(); UT_DEBUGMSG(("Using StringSet [%s]\n",szPathname)); } else { UT_DEBUGMSG(("Unable to load StringSet [%s] -- using builtin strings instead.\n",szPathname)); DELETEP(pDiskStringSet); } g_free(szPathname); } } // AP_App::initilize() calls for us XAP_Win32App::initialize() if (! AP_App::initialize()) return false; // let various window types register themselves if (!AP_Win32Frame::RegisterClass(this)) { UT_DEBUGMSG(("couldn't register class\n")); return false; } ////////////////////////////////////////////////////////////////// // Initialize the importers/exporters ////////////////////////////////////////////////////////////////// IE_ImpExp_RegisterXP (); ////////////////////////////////////////////////////////////////// // initializes the spell checker. ////////////////////////////////////////////////////////////////// { #if ENABLE_SPELL SpellManager::instance(); #endif } // Now we have the strings loaded we can populate the field names correctly int i; for (i = 0; fp_FieldTypes[i].m_Type != FPFIELDTYPE_END; i++) { (&fp_FieldTypes[i])->m_Desc = m_pStringSet->getValue(fp_FieldTypes[i].m_DescId); UT_DEBUGMSG(("Setting field type desc for type %d, desc=%s\n", fp_FieldTypes[i].m_Type, fp_FieldTypes[i].m_Desc)); } for (i = 0; fp_FieldFmts[i].m_Tag != NULL; i++) { (&fp_FieldFmts[i])->m_Desc = m_pStringSet->getValue(fp_FieldFmts[i].m_DescId); UT_DEBUGMSG(("Setting field desc for field %s, desc=%s\n", fp_FieldFmts[i].m_Tag, fp_FieldFmts[i].m_Desc)); } /////////////////////////////////////////////////////////////////////// /// Build a labelset so the plugins can add themselves to something /// /////////////////////////////////////////////////////////////////////// const char * szMenuLabelSetName = NULL; if (getPrefsValue( AP_PREF_KEY_StringSet, (const gchar**)&szMenuLabelSetName) && (szMenuLabelSetName) && (*szMenuLabelSetName)) { ; } else szMenuLabelSetName = AP_PREF_DEFAULT_StringSet; getMenuFactory()->buildMenuLabelSet(szMenuLabelSetName); ////////////////////////////////////////////////////////////////// // Check for necessary DLLs now that we can do localized error messages ////////////////////////////////////////////////////////////////// #if 0 /* re-enable once we use unicows again */ // Ensure that we have Unicows dll if (!UT_IsWinNT()) { HMODULE hModule = LoadLibrary("unicows.dll"); if (!hModule) { UT_String sErr(UT_String_sprintf(m_pStringSet->getValue(AP_STRING_ID_WINDOWS_NEED_UNICOWS), "Unicows")); MessageBox(NULL, sErr.c_str(), NULL, MB_OK); bSuccess = false; } else FreeLibrary(hModule); } #endif // Ensure that common control DLL is loaded HINSTANCE hinstCC = LoadLibrary("comctl32.dll"); UT_return_val_if_fail (hinstCC, false); InitCommonControlsEx_fn pInitCommonControlsEx = NULL; if( hinstCC != NULL ) pInitCommonControlsEx = (InitCommonControlsEx_fn)GetProcAddress( hinstCC, "InitCommonControlsEx" ); if( pInitCommonControlsEx != NULL ) { INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_COOL_CLASSES | ICC_BAR_CLASSES // load the rebar and toolbar | ICC_TAB_CLASSES | ICC_UPDOWN_CLASS // and tab and spin controls ; pInitCommonControlsEx(&icex); } else { InitCommonControls(); UT_String sErr(UT_String_sprintf(m_pStringSet->getValue(AP_STRING_ID_WINDOWS_COMCTL_WARNING), "Unicows")); MessageBox(NULL, sErr.c_str(), NULL, MB_OK); } ////////////////////////////////////////////////////////////////// // load the all Plugins from the correct directory ////////////////////////////////////////////////////////////////// #ifndef DISABLE_BUILTIN_PLUGINS abi_register_builtin_plugins(); #endif bool bLoadPlugins = true; bool bFound = getPrefsValueBool(XAP_PREF_KEY_AutoLoadPlugins,&bLoadPlugins); if(bLoadPlugins || !bFound) { char szPath[PATH_MAX]; char szPlugin[PATH_MAX]; _getExeDir( szPath, PATH_MAX); #ifdef _MSC_VER strcat(szPath, "..\\plugins\\*.dll"); #else strcat(szPath, "..\\lib\\" PACKAGE "-" ABIWORD_SERIES "\\plugins\\*.dll"); #endif struct _finddata_t cfile; long findtag = _findfirst( szPath, &cfile ); if( findtag != -1 ) { do { _getExeDir( szPlugin, PATH_MAX ); #ifdef _MSC_VER strcat( szPlugin, "..\\plugins\\" ); #else strcat( szPlugin, "..\\lib\\" PACKAGE "-" ABIWORD_SERIES "\\plugins\\" ); #endif strcat( szPlugin, cfile.name ); XAP_ModuleManager::instance().loadModule( szPlugin ); } while( _findnext( findtag, &cfile ) == 0 ); } _findclose( findtag ); UT_String pluginName( getUserPrivateDirectory() ); UT_String pluginDir( getUserPrivateDirectory() ); pluginDir += "\\AbiWord\\plugins\\*.dll"; findtag = _findfirst( pluginDir.c_str(), &cfile ); if( findtag != -1 ) { do { pluginName = getUserPrivateDirectory(); pluginName += "\\AbiWord\\plugins\\"; pluginName += cfile.name; XAP_ModuleManager::instance().loadModule( pluginName.c_str() ); } while( _findnext( findtag, &cfile ) == 0 ); } _findclose( findtag ); } return bSuccess; }
bool CSADirRead::GetSubDirs(CCOMList<CSADirEntry> &dir_array, const CCOMString &path) { CCOMString newPath; CCOMString searchString; searchString = path; searchString+= "\\*.*"; try { #ifndef USE_WIN32_FINDFILE struct _finddata_t c_file; long fhandle; if ((fhandle=_findfirst( searchString, &c_file ))!=-1) { // we only care about subdirs if ((c_file.attrib & _A_SUBDIR)==_A_SUBDIR) { // add c_file.name to the string array // we'll handle parents on our own if ((strcmp(c_file.name, ".")!=0) && (strcmp(c_file.name, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+= c_file.name; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } // find the rest of them while(_findnext( fhandle, &c_file ) == 0 ) { if ((c_file.attrib & _A_SUBDIR)==_A_SUBDIR) { // we'll handle parents on our own if ((strcmp(c_file.name, ".")!=0) && (strcmp(c_file.name, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+= c_file.name; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } } _findclose(fhandle); } #else WIN32_FIND_DATA FindFileData; HANDLE hFind; if ((hFind = FindFirstFile(searchString, &FindFileData))!=INVALID_HANDLE_VALUE) { // we only care about files, not subdirs if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY) { // we'll handle parents on our own if ((strcmp(FindFileData.cFileName, ".")!=0) && (strcmp(FindFileData.cFileName, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+=FindFileData.cFileName; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } // find the rest of them while(FindNextFile( hFind, &FindFileData )) { // we only care about files, not subdirs if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==FILE_ATTRIBUTE_DIRECTORY) { // we'll handle parents on our own if ((strcmp(FindFileData.cFileName, ".")!=0) && (strcmp(FindFileData.cFileName, "..")!=0)) { newPath = path; newPath+= "\\"; newPath+=FindFileData.cFileName; GetSubDirs(dir_array, newPath); dir_array.push_back(newPath); } } } } FindClose(hFind); #endif } catch (...) { return false; } return true; }
void HoI3Province::init(int newNumber) { num = newNumber; name = ""; points = 0; metal = oil = rare_materials = energy = manpower = leadership = 0.0; industry = 0; is_coastal = false; is_land = false; is_blacklisted_port = false; avg_mil = 0.0; char sNum[8]; sprintf_s(sNum, 8, "%d", num); string HoI3Loc = Configuration::getHoI3Path(); string parentDir = HoI3Loc + "\\history\\provinces\\*"; string folder; struct _finddata_t dirData; intptr_t dirListing; if ( (dirListing = _findfirst(parentDir.c_str(), &dirData)) != -1L) { do { string filename = HoI3Loc + "\\history\\provinces\\" + dirData.name + "\\" + sNum + "*.txt"; struct _finddata_t fileData; intptr_t fileListing; if ( (fileListing = _findfirst(filename.c_str(), &fileData)) != -1L) { Object* obj = doParseFile( (HoI3Loc + "\\history\\provinces\\" + dirData.name + "\\" + fileData.name).c_str() ); vector<Object*> results = obj->getValue("owner"); if (results.size() > 0) { is_land = true; } results = obj->getValue("points"); if (results.size() > 0) { points = atoi(results[0]->getLeaf().c_str()); } results = obj->getValue("metal"); if (results.size() > 0) { metal = atof(results[0]->getLeaf().c_str()); } results = obj->getValue("crude_oil"); if (results.size() > 0) { oil = atof(results[0]->getLeaf().c_str()); } results = obj->getValue("rare_materials"); if (results.size() > 0) { rare_materials = atof(results[0]->getLeaf().c_str()); } results = obj->getValue("energy"); if (results.size() > 0) { energy = atof(results[0]->getLeaf().c_str()); } results = obj->getValue("manpower"); if (results.size() > 0) { manpower = atof(results[0]->getLeaf().c_str()); } results = obj->getValue("leadership"); if (results.size() > 0) { leadership = atof(results[0]->getLeaf().c_str()); } #ifdef IND_DIAG results = obj->getValue("industry"); if (results.size() > 0) { int temp_industry = atoi(results[0]->getLeaf().c_str()); map<int, int>::iterator itr = industryDistribution.find(temp_industry); if (itr == industryDistribution.end()) industryDistribution[temp_industry] = 1; else ++itr->second; } #endif _findclose(fileListing); break; } _findclose(fileListing); } while (_findnext(dirListing, &dirData) == 0); } _findclose(dirListing); naval_base = air_base = land_fort = coastal_fort = anti_air = infrastructure = 0; // hack for naval bases. some coastal provinces can't have a naval base at all. static vector<int> port_blacklist; if (port_blacklist.size() == 0) { int temp = 0; ifstream s("port_blacklist.txt"); while (s.good() && !s.eof()) { s >> temp; port_blacklist.push_back(temp); } s.close(); }
std::vector<std::string> Utils::getFiles(const std::string& folder, const bool all /* = true */) { std::vector<std::string> files; std::list<std::string> subfolders; subfolders.push_back(folder); #ifdef OS_WINDOWS while (!subfolders.empty()) { std::string current_folder(subfolders.back()); if (*(current_folder.end() - 1) != '/') { current_folder.append("/*"); } else { current_folder.append("*"); } subfolders.pop_back(); struct _finddata_t file_info; long file_handler = _findfirst(current_folder.c_str(), &file_info); while (file_handler != -1) { if (all && (!strcmp(file_info.name, ".") || !strcmp(file_info.name, ".."))) { if (_findnext(file_handler, &file_info) != 0) break; continue; } if (file_info.attrib & _A_SUBDIR) { // it's a sub folder if (all) { // will search sub folder std::string folder(current_folder); folder.pop_back(); folder.append(file_info.name); subfolders.push_back(folder.c_str()); } } else { // it's a file std::string file_path; // current_folder.pop_back(); file_path.assign(current_folder.c_str()).pop_back(); file_path.append(file_info.name); files.push_back(file_path); } if (_findnext(file_handler, &file_info) != 0) break; } // while _findclose(file_handler); } #elif defined(OS_LINUX) || defined(OS_UNIX) while (!subfolders.empty()) { std::string current_folder(subfolders.back()); if (*(current_folder.end() - 1) != '/') { current_folder.push_back('/'); } DIR* pdir = opendir(current_folder.c_str()); subfolders.pop_back(); if (!pdir) { continue; } dirent* dir = NULL; while ((dir = readdir(pdir)) != NULL) { // iterates the current folder, search file & sub folder struct stat st; if (all && (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))) { // must ignore . & .. continue; } if (!strcmp(dir->d_name, ".DS_Store")) { // in OSX, 'finder' will create .DS_Store continue; } std::string file_path; file_path.append(current_folder.c_str()); file_path.append(dir->d_name); if (lstat(file_path.c_str(), &st) < 0) { // perror("lstat"); continue; } if (S_ISDIR(st.st_mode)) { // it's a sub folder if (all) { // will search sub folder std::string subfolder(current_folder); subfolder.append(dir->d_name); subfolders.push_back(subfolder.c_str()); } } else { // it's a file files.push_back(file_path); } } // while closedir(pdir); } #endif return files; }
//----------------------------------------------------------------------------- // program entry point. //----------------------------------------------------------------------------- int main(int argc, char *argv[], char *envp[]) { //------------------------------------------------------------------------- // Generic variables. //------------------------------------------------------------------------- int ret = -1; PENERGY_DATA p = NULL; PL_STATUS plret = PL_FAILURE; unsigned long long value = 0; char buffer[ENERGY_INPUT_LINE_MAX_SIZE] = { '\0' }; #ifdef __PL_WINDOWS__ BOOL bret = FALSE; #endif // __PL_WINDOWS__ //------------------------------------------------------------------------- // ESRV instance handling variables. //------------------------------------------------------------------------- char esrv_config_file_name_buffer[PL_MAX_PATH] = { '\0' }; int f_esrv_guid = 0; int f_esrv_pid = 0; char *env = NULL; //------------------------------------------------------------------------- // Variables used to build ESRV start command -- if we have to. //------------------------------------------------------------------------- char esrv_command_buffer[PL_MAX_PATH] = { '\0' }; //------------------------------------------------------------------------- // Variables used to remove ESRV PL after use -- if we started it. //------------------------------------------------------------------------- char esrv_pl_path_name[PL_MAX_PATH] = { '\0' }; #ifdef __PL_WINDOWS__ char current_path_name[PL_MAX_PATH] = { '\0' }; char esrv_pl_config_file_name[PL_MAX_PATH] = { '\0' }; struct _finddata_t find_files; intptr_t file = 0; #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) DIR *directory = NULL; struct dirent *file = NULL; char file_name[PL_MAX_PATH] = { '\0' }; #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ //------------------------------------------------------------------------- // Variables used to read ESRV's sartup output -- used to get the GUID //------------------------------------------------------------------------- char *pc = NULL; char *token = NULL; int input_line_count = 0; char esrv_guid[ENERGY_GUID_LENGHT_IN_CHARACTERS + 1] = { '\0' }; #ifdef __PL_WINDOWS__ DWORD esrv_pid = 0; HANDLE esrv_handle = NULL; DWORD bytes_read = 0; #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) pid_t esrv_pid = 0; #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ //------------------------------------------------------------------------- // Signal handler variables. //------------------------------------------------------------------------- #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) struct sigaction sa; #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ //-------------------------------------------------------------------------- //------------------------------------------------------------------------- // Retrive the energy structure address. //------------------------------------------------------------------------- p = &energy_data; assert(p != NULL); //------------------------------------------------------------------------- // Initialize the energy data structure. //------------------------------------------------------------------------- memset(p, 0, sizeof(ENERGY_DATA)); p->argc = argc; p->argv = argv; p->channel = ENERGY_DEFAULT_CHANNEL; p->esrv_pld = PL_INVALID_DESCRIPTOR; p->esrv_status = ESRV_STATUS_NOT_RUNNING; //------------------------------------------------------------------------- // Parse user input. //------------------------------------------------------------------------- plret = parser(&energy_data); if(plret != PL_SUCCESS) { _ERROR("Unable to make sense of user input."); } else { if((p->f_help == 1) || (p->f_version == 1)) { goto done; } } //------------------------------------------------------------------------- // Check for inconsistent user input. //------------------------------------------------------------------------- if( ( (p->f_guid == 1) && (p->f_guid_shell_variable) ) ) { _ERROR( "Incompatible ESRV instance designation. Please use --guid or --guid_shell_variable option." ); } if(p->f_command == 0) { _ERROR( "You need to specify a command. Use energy --help for details." ); } //------------------------------------------------------------------------- // Select the ESRV instance to use. // Note: // If no ESRV id is provided, then an instance is started and ended // by the program. // Note: // If GUID is provided, build the pl_config.ini full path name for the // attach. // Note: // If CONFIG is provided, then do nothing, we are ready to attach. //------------------------------------------------------------------------- memset( esrv_config_file_name_buffer, 0, sizeof(esrv_config_file_name_buffer) ); if(p->f_guid == 1) { memcpy( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_ROOT, strlen(ENERGY_ESRV_PL_CONFIG_FILE_ROOT) ); strncat( esrv_config_file_name_buffer, ESRV_APPLICATION_NAME, strlen(ESRV_APPLICATION_NAME) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE, strlen(ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE) ); strncat( esrv_config_file_name_buffer, p->esrv_guid, strlen(p->esrv_guid) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_NAME, strlen(ENERGY_ESRV_PL_CONFIG_FILE_NAME) ); goto attach_to_esrv; } if(p->f_guid_shell_variable == 1) { memcpy( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_ROOT, strlen(ENERGY_ESRV_PL_CONFIG_FILE_ROOT) ); strncat( esrv_config_file_name_buffer, ESRV_APPLICATION_NAME, strlen(ESRV_APPLICATION_NAME) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE, strlen(ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE) ); strncat( esrv_config_file_name_buffer, p->esrv_guid_shell_variable_value, strlen(p->esrv_guid_shell_variable_value) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_NAME, strlen(ENERGY_ESRV_PL_CONFIG_FILE_NAME) ); goto attach_to_esrv; } //------------------------------------------------------------------------- // Because it is easier to type energy -- command than energy --guid xxx -- // command, we check for the existence of a ENERGY_ESRV_DEFAULT_GUID_SHELL_- // -VARIABLE shell variable. If it exist and has a valid GUID, then it is // used. If no such variable exist, then energy continues by starting its // own instance of ESRV. //------------------------------------------------------------------------- env = getenv(ENERGY_ESRV_DEFAULT_GUID_SHELL_VARIABLE); if(env != NULL) { ret = plh_filter_uuid_string(env); if(ret != PL_FAILURE) { memcpy( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_ROOT, strlen(ENERGY_ESRV_PL_CONFIG_FILE_ROOT) ); strncat( esrv_config_file_name_buffer, ESRV_APPLICATION_NAME, strlen(ESRV_APPLICATION_NAME) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE, strlen(ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE) ); strncat( esrv_config_file_name_buffer, env, strlen(env) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_NAME, strlen(ENERGY_ESRV_PL_CONFIG_FILE_NAME) ); goto attach_to_esrv; } } //------------------------------------------------------------------------- // Build ESRV binary name and command line // Note: // cli_buffer holds the ESRV binary name and the command line options. // if the command and the arguments are provided separately to // CreateProcess then the argv count is erroneous in the started // process and ESRV fails the cli parsing. //------------------------------------------------------------------------- memset( esrv_command_buffer, 0, sizeof(esrv_command_buffer) ); strncpy( esrv_command_buffer, ENERGY_ESRV_BINARY_NAME, strlen(ENERGY_ESRV_BINARY_NAME) ); if(p->f_esrv_options == 1) { strncat( esrv_command_buffer, p->esrv_options, strlen(p->esrv_options) ); } else { strncat( esrv_command_buffer, ENERGY_ESRV_DEFAULT_OPTIONS, strlen(ENERGY_ESRV_DEFAULT_OPTIONS) ); } strncat( esrv_command_buffer, ENERGY_ESRV_SHELL_OPTION, strlen(ENERGY_ESRV_SHELL_OPTION) ); //------------------------------------------------------------------------- // Start an ESRV instance in a child process. //------------------------------------------------------------------------- #ifdef __PL_WINDOWS__ p->fp_esrv = _popen( esrv_command_buffer, "rt" ); #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) p->fp_esrv = popen( esrv_command_buffer, "r" ); #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ if(p->fp_esrv == NULL) { _ERROR("Unable to start ESRV."); } //------------------------------------------------------------------------- // Retrieve the ESRV's instance PID and GUID. //------------------------------------------------------------------------- do { pc = fgets( buffer, sizeof(buffer), p->fp_esrv ); if(pc != NULL) { switch(++input_line_count) { case ENERGY_ESRV_GUID_LINE: //--------------------------------------------------------- // extract ESRV's GUID and save it //--------------------------------------------------------- token = strtok( buffer, ENERGY_ESRV_GUID_TOKEN_SEPARATORS ); while(token != NULL) { if(strncmp( token, ENERGY_ESRV_PRE_GUID_TOKEN, strlen(ENERGY_ESRV_PRE_GUID_TOKEN) ) == 0) { token = strtok( NULL, ENERGY_ESRV_GUID_TOKEN_TERMINATOR ); memset( esrv_guid, 0, sizeof(esrv_guid) ); strncpy( esrv_guid, token, strlen(token) ); f_esrv_guid = 1; break; } token = strtok( NULL, ENERGY_ESRV_GUID_TOKEN_SEPARATORS ); } break; case ENERGY_ESRV_PID_LINE: //--------------------------------------------------------- // extract ESRV's PID and save it. //--------------------------------------------------------- token = strtok( buffer, ENERGY_ESRV_PID_TOKEN_SEPARATORS ); while(token != NULL) { if(strncmp( token, ENERGY_ESRV_PRE_PID_TOKEN, strlen(ENERGY_ESRV_PRE_PID_TOKEN) ) == 0) { token = strtok( NULL, ENERGY_ESRV_PID_TOKEN_TERMINATOR ); #ifdef __PL_WINDOWS__ esrv_pid = (DWORD)atoi(token); #endif // __Pl_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) esrv_pid = (pid_t)atoi(token); #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ assert(esrv_pid != 0); f_esrv_pid = 1; goto pid_found; } token = strtok( NULL, ENERGY_ESRV_GUID_TOKEN_SEPARATORS ); } break; default: break; } } else { //----------------------------------------------------------------- // Likely the ESRV launch has failed, let's signal this error. //----------------------------------------------------------------- _ERROR("ESRV likely failed to start."); } } while(pc != NULL); //------------------------------------------------------------------------- // Likely the ESRV launch has failed, let's signal this error. //------------------------------------------------------------------------- _ERROR("ESRV likely failed to start."); pid_found: //------------------------------------------------------------------------- // Check and build the pl_config.ini file to attach to. //------------------------------------------------------------------------- assert((f_esrv_guid == 1) && (f_esrv_pid == 1)); memset( esrv_config_file_name_buffer, 0, sizeof(esrv_config_file_name_buffer) ); memcpy( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_ROOT, strlen(ENERGY_ESRV_PL_CONFIG_FILE_ROOT) ); strncat( esrv_config_file_name_buffer, ESRV_APPLICATION_NAME, strlen(ESRV_APPLICATION_NAME) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE, strlen(ENERGY_ESRV_PL_CONFIG_FILE_UNDERSCORE) ); strncat( esrv_config_file_name_buffer, esrv_guid, strlen(esrv_guid) ); memset( esrv_pl_path_name, 0, sizeof(esrv_pl_path_name) ); strncpy( esrv_pl_path_name, esrv_config_file_name_buffer, strlen(esrv_config_file_name_buffer) ); strncat( esrv_config_file_name_buffer, ENERGY_ESRV_PL_CONFIG_FILE_NAME, strlen(ENERGY_ESRV_PL_CONFIG_FILE_NAME) ); attach_to_esrv: //------------------------------------------------------------------------- // Attach to the identified instance of ESRV and read settings. //------------------------------------------------------------------------- p->esrv_pld = pl_attach(esrv_config_file_name_buffer); if(p->esrv_pld == PL_INVALID_DESCRIPTOR) { _ERROR("Unable to attach to the specified ESRV instance."); } //------------------------------------------------------------------------- // read-in esrv's configuration: // - ESRV Status (running or not) // - ESRV Channel count // - ESRV Version (not used) // - ESRV energy in joule counter's precision // Note: // since each channel holds esrv's configuration counters, we read the // first channel to read the channel count. ESRV has always at least // one channel, so the read is safe // Note: // Channel count is zero count, therefore the --. //------------------------------------------------------------------------- plret = pl_read( p->esrv_pld, &p->channels, ESRV_COUNTER_CHANNELS_INDEX ); if(plret != PL_SUCCESS) { _ERROR("Unable to read the ESRV channels count counter."); } if(p->channel > p->channels) { WARNING( "The requested channel does not exist in the specified ESRV instance. Will use default channel (1)." ); p->channel = 1; } p->channel--; //------------------------------------------------------------------------- // Now that the channels count is known, we can read the requested ESRV channel //------------------------------------------------------------------------- plret = pl_read( p->esrv_pld, &p->status, (p->channel * ESRV_BASE_COUNTERS_COUNT) + ESRV_COUNTER_STATUS_INDEX ); if(plret != PL_SUCCESS) { _ERROR("Unable to read the ESRV status counter."); } if(p->status != ESRV_STATUS_RUNNING) { _ERROR("The specified ESRV instance doesn't seem to be alive."); } plret = pl_read( p->esrv_pld, &p->version, (p->channel * ESRV_BASE_COUNTERS_COUNT) + ESRV_COUNTER_VERSION_INDEX ); if(plret != PL_SUCCESS) { _ERROR("Unable to read the ESRV version counter."); } plret = pl_read( p->esrv_pld, &value, (p->channel * ESRV_BASE_COUNTERS_COUNT) + ESRV_COUNTER_ENERGY_JOULES_DECIMALS_INDEX ); if(plret != PL_SUCCESS) { _ERROR( "Unable to read the ESRV energy in Joule(s) counter's .decimal suffix counter." ); } p->energy_data_multiplier = pow( 10.0, (double)value ); //------------------------------------------------------------------------- // Install signal handler. //------------------------------------------------------------------------- #ifdef __PL_WINDOWS__ bret = SetConsoleCtrlHandler( (PHANDLER_ROUTINE)signal_handler, TRUE ); if(bret == 0) { #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) sa.sa_handler = signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; ret = sigaction( SIGINT, &sa, NULL ); if(ret == -1) { #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ _ERROR("Unable to install the signal handler."); } //------------------------------------------------------------------------- // Read start energy. //------------------------------------------------------------------------- plret = pl_read( p->esrv_pld, &p->start_energy_data, (p->channel * ESRV_BASE_COUNTERS_COUNT) + ESRV_COUNTER_ENERGY_JOULES_INDEX ); if(plret != PL_SUCCESS) { _ERROR("Unable to read start energy value."); } //------------------------------------------------------------------------- // Run command. //------------------------------------------------------------------------- #ifdef __PL_WINDOWS__ p->fp = _popen( p->command, "rt" ); #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) p->fp = popen( p->command, "r" ); #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ if(p->fp == NULL) { _ERROR("Unable to execute command."); } //------------------------------------------------------------------------- // Echo command output to stdout. // Note: // With some verbose commands, the extra processing on the output may // consume extra energy (buffer[strlen(buffer) - 1] = '\0';). Remove // this cosmetic processing if this becomes an issue. //------------------------------------------------------------------------- while(p->f_interrupted == 0) { pc = fgets( buffer, sizeof(buffer), p->fp ); if(pc != NULL) { buffer[strlen(buffer) - 1] = '\0'; puts(buffer); } else { break; } } //------------------------------------------------------------------------- // Read end energy and close ESRV PL. //------------------------------------------------------------------------- plret = pl_read( p->esrv_pld, &p->end_energy_data, (p->channel * ESRV_BASE_COUNTERS_COUNT) + ESRV_COUNTER_ENERGY_JOULES_INDEX ); if(plret != PL_SUCCESS) { _ERROR("Unable to read end energy value."); } plret = pl_close(p->esrv_pld); if(plret != PL_SUCCESS) { _ERROR("Unable to close ESRV instance's PL."); } //------------------------------------------------------------------------- // End command. //------------------------------------------------------------------------- if(p->f_interrupted == 0) { if(feof(p->fp)) { #ifdef __PL_WINDOWS__ _pclose(p->fp); #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) pclose(p->fp); #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ } else { _ERROR("Unable to completely read command's output."); } } //------------------------------------------------------------------------- // Compute energy consumed. //------------------------------------------------------------------------- p->consumed_energy_in_joules = (double)( p->end_energy_data - p->start_energy_data ) / p->energy_data_multiplier ; p->consumed_energy_in_kwhs = p->consumed_energy_in_joules / ONE_KWH_IN_JOULES ; //------------------------------------------------------------------------- // Report consumed energy. //------------------------------------------------------------------------- fprintf( stdout, "\nEnergy: [%g] Joule(s) - [%g] kWh(s).\n", p->consumed_energy_in_joules, p->consumed_energy_in_kwhs ); //------------------------------------------------------------------------- // close the ESRV instance's process and remove its PL //------------------------------------------------------------------------- if( (f_esrv_guid == 1) && (f_esrv_pid == 1) ) { #ifdef __PL_WINDOWS__ esrv_handle = OpenProcess( PROCESS_TERMINATE, FALSE, esrv_pid ); assert(esrv_handle != NULL); bret = TerminateProcess( esrv_handle, 0 ); assert(bret != FALSE); //--------------------------------------------------------------------- // reset last ESRV instance's flags and ids //--------------------------------------------------------------------- esrv_handle = NULL; #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) ret = kill( esrv_pid, SIGTERM ); assert(ret != -1); #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ f_esrv_guid = 0; f_esrv_pid = 0; esrv_pid = 0; //--------------------------------------------------------------------- // close last ESRV instance's output stream //--------------------------------------------------------------------- #ifdef __PL_WINDOWS__ _pclose(p->fp_esrv); #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) pclose(p->fp_esrv); #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ //--------------------------------------------------------------------- // Delete ESRV instance's PL. //--------------------------------------------------------------------- #ifdef __PL_WINDOWS__ pc = _getcwd( current_path_name, sizeof(current_path_name) ); assert(pc != NULL); ret = _chdir(esrv_pl_path_name); assert(ret != -1); file = _findfirst( "*", &find_files ); do { if( ( strcmp( find_files.name, "." ) != 0 ) && ( strcmp( find_files.name, ".." ) != 0 ) ) { ret = -1; do { ret = remove(find_files.name); } while(ret == -1); } } while( _findnext( file, &find_files ) == 0); ret = _findclose(file); assert(ret != -1); ret = _chdir(current_path_name); assert(ret != -1); ret = -1; do { ret = _rmdir(esrv_pl_path_name); } while(ret == -1); #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) directory = opendir(esrv_pl_path_name); assert(directory != NULL); file = readdir(directory); while(file != NULL) { if( ( strcmp( file->d_name, "." ) != 0 ) && ( strcmp( file->d_name, ".." ) != 0 ) ) { memset( file_name, 0, sizeof(file_name) ); strncat( file_name, esrv_pl_path_name, strlen(esrv_pl_path_name) ); strncat( file_name, "/", strlen("/") ); strncat( file_name, file->d_name, strlen(file->d_name) ); ret = -1; do { ret = unlink(file_name); } while(ret != -1); } file = readdir(directory); } closedir(directory); ret = -1; do { ret = rmdir(esrv_pl_path_name); } while(ret != -1); #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ } done: return(PL_SUCCESS); error: return(PL_FAILURE); } /*----------------------------------------------------------------------------- Function: parser Purpose : parse user input to set energy data structure In : pointer to energy data structure Out : updated energy data structure Return : status History ------------------------------------------------------------------------------- Date : Author Modification ------------------------------------------------------------------------------- 01/28/2010 Jamel Tayeb Creation. */ int parser(PENERGY_DATA p) { //------------------------------------------------------------------------- // Parsing variables. //------------------------------------------------------------------------- int i = 0; int j = 0; int value = 0; char buffer[PL_MAX_PATH] = { '\0' }; char *options[OPTION_STRINGS_COUNT] = { OPTION_STRINGS }; #ifdef __PL_WINDOWS__ size_t st_ret = 0; #endif // __PL_WINDOWS__ PL_STATUS ret = PL_FAILURE; //------------------------------------------------------------------------- // String to upper case variables. //------------------------------------------------------------------------- #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) size_t k = 0; size_t l = 0; char *pc = NULL; char c = '\0'; #endif // __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ assert(p != NULL); for(i = 1; i < p->argc; i++) { memset(buffer, 0, sizeof(buffer)); strncpy(buffer, p->argv[i], sizeof(buffer)); #ifdef __PL_WINDOWS__ _strupr(buffer); #endif // __PL_WINDOWS__ #if defined (__PL_LINUX__) || (__PL_SOLARIS__) || (__PL_MACOSX__) pc = buffer; l = strlen(buffer); for(k = 0; k < l; k++) { c = *pc; *pc++ = (char)toupper(c); } #endif// __PL_LINUX__ || __PL_SOLARIS__ || __PL_MACOSX__ for(j = 0; j < OPTION_STRINGS_COUNT; j++) { if(strncmp(buffer, options[j], strlen(options[j])) == 0) { switch(j) { //--------------------------------------------------------- // [-H] option. //--------------------------------------------------------- case H_ID: case HELP_ID: fprintf( stdout, HELP_STRING, ENERGY_APPLICATION_NAME, ENERGY_APPLICATION_NAME, ENERGY_APPLICATION_NAME, ENERGY_ESRV_DEFAULT_GUID_SHELL_VARIABLE, ENERGY_APPLICATION_NAME, ENERGY_APPLICATION_NAME, ENERGY_APPLICATION_NAME ); p->f_help = 1; goto parser_done; break; //--------------------------------------------------------- // [-V] option. //--------------------------------------------------------- case V_ID: case VERSION_ID: p->f_version = 1; fprintf( stdout, "%s: version %s.%s.%s\n", ENERGY_APPLICATION_NAME, ENERGY_VERSION_MAJOR, ENERGY_VERSION_MINOR, ENERGY_VERSION_REVISION ); fprintf( stdout, "Using PL helper version %s.%s.%s\n", PL_HELPER_VERSION_MAJOR, PL_HELPER_VERSION_MINOR, PL_HELPER_VERSION_REVISION ); fprintf( stdout, "Using PL version %s.%s.%s(%s)", PL_VERSION_MAJOR, PL_VERSION_MINOR, PL_VERSION_REVISION, PL_VERSION_OS ); fprintf(stdout, "\n"); goto parser_done; break; //--------------------------------------------------------- // [-G <string>] option. //--------------------------------------------------------- case G_ID: case GUID_ID: if(i + 1 >= p->argc) { ERROR_INDEX( "Missing argument after token [%s] in position [%d].", p->argv[i], i + 1 ); } p->f_guid = 1; i++; p->esrv_guid = p->argv[i]; ret = plh_filter_uuid_string(p->esrv_guid); if(ret == PL_FAILURE) { memset(buffer, 0, sizeof(buffer)); sprintf( buffer, "Guid [%s] does not seem to be a valig guid.", p->esrv_guid ); _ERROR(buffer); } goto parser_skip; break; //--------------------------------------------------------- // [-X <string>] option. //--------------------------------------------------------- case X_ID: case GUID_SHELL_VARIABLE_ID: if(i + 1 >= p->argc) { ERROR_INDEX( "Missing argument after token [%s] in position [%d].", p->argv[i], i + 1 ); } p->f_guid_shell_variable = 1; i++; p->esrv_guid_shell_variable = p->argv[i]; p->esrv_guid_shell_variable_value = getenv(p->esrv_guid_shell_variable); if(p->esrv_guid_shell_variable_value == NULL) { memset(buffer, 0, sizeof(buffer)); sprintf( buffer, "Environment variable [%s] does not exist.", p->esrv_guid_shell_variable ); _ERROR(buffer); } else { ret = plh_filter_uuid_string(p->esrv_guid_shell_variable_value); if(ret == PL_FAILURE) { memset(buffer, 0, sizeof(buffer)); sprintf( buffer, "Environment variable [%s] value [%s] does not seem to be a valig guid.", p->esrv_guid_shell_variable, p->esrv_guid_shell_variable_value ); _ERROR(buffer); } } goto parser_skip; break; //--------------------------------------------------------- // [-N <integer>] option. //--------------------------------------------------------- case N_ID: case CHANNEL_ID: if(i + 1 >= p->argc) { ERROR_INDEX( "Missing argument after token [%s] in position [%d].", p->argv[i], i + 1 ); } i++; p->channel = (unsigned int)atoi(p->argv[i]); if(value == 0) { value = ENERGY_DEFAULT_CHANNEL; } p->f_channel = 1; goto parser_skip; break; //--------------------------------------------------------- // [-E <string>] option. //--------------------------------------------------------- case E_ID: case ESRV_OPTIONS_ID: if(i + 1 >= p->argc) { ERROR_INDEX( "Missing argument after token [%s] in position [%d].", p->argv[i], i + 1 ); } p->f_esrv_options = 1; i++; p->esrv_options = p->argv[i]; goto parser_skip; break; //--------------------------------------------------------- // -- separator id. //--------------------------------------------------------- case SEPARATOR_ID: if(i + 1 >= p->argc) { ERROR_INDEX( "Missing argument after token [%s] in position [%d].", p->argv[i], i + 1 ); } i++; memset(p->command, 0, sizeof(p->command)); strncpy(p->command, p->argv[i], strlen(p->argv[i])); while(++i < p->argc) { strncat(p->command, " ", strlen(" ")); strncat(p->command, p->argv[i], strlen(p->argv[i])); } p->f_command = 1; goto parser_done; break; //--------------------------------------------------------- // Unknown option. //--------------------------------------------------------- default: ERROR_INDEX( "Unable to make sense of token [%s] in position [%d].", buffer, j ); } } } // for j _ERROR("Unable to make sense of options. Use --help option for help."); goto error; parser_skip: ; } // for i parser_done: //------------------------------------------------------------------------- // Return status. //------------------------------------------------------------------------- return(PL_SUCCESS); error: return(PL_FAILURE); }