Пример #1
1
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();
}
Пример #2
0
bool get_basename_from_extension(
			std::vector<std::string> &list,
			const std::string &path,
			const std::string &extension,
			bool strip_extension )
{
#ifdef SFML_SYSTEM_WINDOWS
	std::string temp = path;
	if ( !path.empty()
			&& ( path[path.size()-1] != '/' )
			&& ( path[path.size()-1] != '\\' ))
		temp += "/";

	temp += "*" + extension;

	struct _finddata_t t;
	intptr_t srch = _findfirst( temp.c_str(), &t );

	if  ( srch < 0 )
		return false;

	do
	{
		std::string what;
		str_from_c( what, t.name );

		// I don't know why but the search filespec we are using
		// "path/*.ext"seems to also match "path/*.ext*"... so we
		// do the tail comparison below on purpose to catch this...
#else
	DIR *dir;
	struct dirent *ent;

	if ( (dir = opendir( path.c_str() )) == NULL )
		return false;

	while ((ent = readdir( dir )) != NULL )
	{
		std::string what;
		str_from_c( what, ent->d_name );
#endif

		if ( ( what.compare( "." ) == 0 ) || ( what.compare( ".." ) == 0 ) )
			continue;

		if ( tail_compare( what, extension ) )
		{
			if ( strip_extension && ( what.size() > extension.size() ))
			{
				std::string bname = what.substr( 0,
					what.size() - extension.size() );

				// don't add duplicates if we are stripping extension
				// example: if there is both foo.zip and foo.7z
				//
				if ( list.empty() || ( bname.compare( list.back() ) != 0 ))
					list.push_back( bname );
			}
			else
				list.push_back( what );

		}
#ifdef SFML_SYSTEM_WINDOWS
	} while ( _findnext( srch, &t ) == 0 );
	_findclose( srch );
#else
	}
	closedir( dir );
#endif

	return !(list.empty());
}
Пример #3
0
std::vector<std::string>* findfile(char* pattern, char* dir){
	std::vector<std::string>* r = new std::vector<std::string>;
	long findhandle = -1;
#ifndef WIN32
	struct dirent **namelist;
	char szScriptName[256];
	int n;
	pFor = pValue;
	n=scandir(g_szScriptPath ,&namelist, select_file,alphasort);
	if (n<0)
		perror("scandir");
	else
	{
		while(n--)
		{
			memset(szScriptName, 0, 256);
			snprintf(szScriptName, 255, "%s/%s", g_szScriptPath, namelist[n]->d_name); 
			free(namelist[n]);
			printf("compilering %s\n",szScriptName);
			if (compiler.Compile(szScriptName))
			{
				snprintf(szMsg, 300,"SE:: compile \"%s\" succeeded", szScriptName);
				g_pLogFunc(szMsg, __FILE__, __LINE__ , 1);
				printf(szMsg);
				printf("\n");
			}
			else
			{
				snprintf(szMsg, 300,"SE:: compile \"%s\" failed, error msg from compiler:\"%s\"",
					szScriptName, compiler.GetErrMsg());
				g_pLogFunc(szMsg, __FILE__, __LINE__ , 1);
				printf(szMsg);
				printf("\n");

				lRet = -1;
				goto out;
			}
		}
		free(namelist);
	}
#else
	char szScriptFileMask[_MAX_PATH];
	sprintf(szScriptFileMask, "%s%s%s", dir, PATH_SEPARATOR_S, pattern);
	_finddata_t finddata;
	findhandle = _findfirst(szScriptFileMask, &finddata);
	if (findhandle != -1)
	{
		int ret;
		ret = 0;
		while (ret != -1)
		{

			if (finddata.name[0] != '.')
			{
				if (finddata.attrib == _A_SUBDIR){
					char sub_dir[_MAX_PATH] = "";
					snprintf(sub_dir, _MAX_PATH -1, "%s\\%s", dir, finddata.name);
					std::vector<std::string>* rr = findfile("*", sub_dir);
					for (int i = 0; i< rr->size(); i++){
						r->push_back(((*rr)[i]).c_str());
					}
					Delete(rr);
				}
				else{
					char szScriptFile[256] = "";
					sprintf(szScriptFile, "%s\\%s", dir, finddata.name);
					r->push_back(szScriptFile);
				}
			}
			memset(&finddata, 0, sizeof(_finddata_t));
			ret = _findnext(findhandle, &finddata);
		}
	}
#endif
	return r;
}	
Пример #4
0
/*
 *-----------------------------------------------------------------------
 *
 * collect_tests_from_dir --
 *
 *       Recursively search the directory at @dir_path for files with
 *       '.json' in their filenames. Append all found file paths to
 *       @paths, and return the number of files found.
 *
 *-----------------------------------------------------------------------
 */
int
collect_tests_from_dir (char (*paths)[MAX_TEST_NAME_LENGTH] /* OUT */,
                        const char *dir_path,
                        int paths_index,
                        int max_paths)
{
#ifdef _MSC_VER
   intptr_t handle;
   struct _finddata_t info;

   char child_path[MAX_TEST_NAME_LENGTH];

   handle = _findfirst(dir_path, &info);

   if (handle == -1) {
      return 0;
   }

   while (1) {
      assert(paths_index < max_paths);

      if (_findnext(handle, &info) == -1) {
         break;
      }

      if (info.attrib & _A_SUBDIR) {
         /* recursively call on child directories */
         if (strcmp (info.name, "..") != 0 &&
             strcmp (info.name, ".") != 0) {

            assemble_path(dir_path, info.name, child_path);
            paths_index = collect_tests_from_dir(paths, child_path, paths_index, max_paths);
         }
      } else if (strstr(info.name, ".json")) {
         /* if this is a JSON test, collect its path */
         assemble_path(dir_path, info.name, paths[paths_index++]);
      }
   }

   _findclose(handle);

   return paths_index;
#else
   struct dirent *entry;
   struct stat dir_stat;
   char child_path[MAX_TEST_NAME_LENGTH];
   DIR *dir;

   dir = opendir(dir_path);
   assert (dir);
   while ((entry = readdir(dir))) {
      assert(paths_index < max_paths);

      if (0 == stat(entry->d_name, &dir_stat) && dir_stat.st_mode & S_IFDIR) {
         /* recursively call on child directories */
         if (strcmp (entry->d_name, "..") != 0 &&
             strcmp (entry->d_name, ".") != 0) {

            assemble_path(dir_path, entry->d_name, child_path);
            paths_index = collect_tests_from_dir(paths, child_path, paths_index,
                                                 max_paths);
         }
      } else if (strstr(entry->d_name, ".json")) {
         /* if this is a JSON test, collect its path */
         assemble_path(dir_path, entry->d_name, paths[paths_index++]);
      }
   }

   closedir(dir);

   return paths_index;
#endif
}
Пример #5
0
int
osd_ffi_(char *dir, char *name, char *tab_res, int *max, int l_dir, int l_name, int l_tab)
{
     char file[255], directory[255];
     int  ii, jj, kk, nb_file;
#ifdef VAC
     BOOL  fini ;
#else
     int  fini ;
#endif

     /***** Le Nom de la directory ******/
      if (*dir == ' ') {
          directory[0] = '.';
          directory[1] = '/';
          directory[2] = 0 ;
      }
      else {
          for (ii=0; ii<l_dir && ii<255 && *dir != ' '; ii++) {
             directory[ii] = *(dir++);
             if ( directory [ii] == '\\' ) directory [ii] = '/' ;
          }
          directory[ii]=0;
      }

      /***** Le Nom de fichier recherche *******/
      for (ii=0; ii<l_name  && ii<255 && *name != ' '; ii++)
             file[ii] = *(name++);
      file[ii]=0;

      /****** On ouvre le directory pour trouver les fichiers ********/
      nb_file=0;

      strcpy(filespec, directory );
      strcat(filespec, file );

#ifdef VAC
      if ((dirp = FindFirstFile(filespec, zeptr)) != INVALID_HANDLE_VALUE ) {
#else
      if ((dirp = _findfirst(filespec, &zeptr)) != -1 ) {
#endif
          fini = 0 ;
          while (nb_file < *max && (! fini ) ) {

              /*====== Si on trouve un fichier qui lui ressemble ==========*/


                 /*======= On copie sa valeur ========*/
                 /*        avec la directorie         */
                 /* jj tab_res, kk la ligne ,ii le nom */
                 jj = nb_file * l_tab;
                 kk = 0;
                 if (directory[0] != '.') {
                    for (; kk<l_tab && directory[kk] != 0; kk++,jj++)
                        *(tab_res + jj) = directory[kk];

                    if (directory[kk-1] != '/')  *(tab_res + (jj++)) = '/';
                 }

#ifdef VAC
                 for (ii=0; (kk)<l_tab && *((*zeptr).cFileName+ii); ii++,jj++,kk++)
                     *(tab_res + jj) = *((*zeptr).cFileName + ii);
#else
                 for (ii=0; (kk)<l_tab && *(zeptr.name+ii); ii++,jj++,kk++)
                     *(tab_res + jj) = *(zeptr.name + ii);
#endif

                 /*======= En completant avec blanc ======*/

                 for (; kk<l_tab ; jj++,kk++)
                     *(tab_res + jj) = ' ';
                 nb_file++;

#ifdef VAC
	      fini = FindNextFile(dirp, zeptr );
#else
	      fini = _findnext(dirp, &zeptr );
#endif
          }
      }
/***** pas de tri du tableau tab_res par ordre alpha *****/

#ifdef VAC
	  if (dirp != INVALID_HANDLE_VALUE) FindClose(dirp);
#else
	  if (dirp) _findclose(dirp);
#endif

      return(nb_file);
}
Пример #6
0
int main(int argc, char * argv[])
{
	FILE *fpPak,	//所需生成的总文件
	     *fpSrc;	//各个包
#ifdef PAK_NAME_DEBUG
	FILE *fpPakNameTxt;
#endif		
	PakInfo tPakInfo [MAX_FILE_COUNT] = {0};
	char srcName[MAX_FILE_NAME_LENGTH];
	char strOutName[MAX_FILE_NAME_LENGTH] = "stcm.narc";
	char strPakDir [MAX_FILE_NAME_LENGTH] = "./stcm";
	char strPakName [MAX_FILE_COUNT] [ MAX_FILE_NAME_LENGTH ] = {0};
	BYTE *dat;
	BYTE byteTmp;
	struct _finddata_t c_file;
	intptr_t hFile;
	int iCount = 0, c;
	ULONG	ulPakCount = 0,
		ulPakLengthSum,
		ulOutLength;

	while ( -1 != (c = getopt (argc, argv, "i:o:")))
		switch (c)
		{
			case 'i':
				if ('-' == optarg[0])
				{
					printf ("Option -%c requires an argument.\n", c);
					exit (0);
				}
				strcpy (strPakDir, optarg);
				break;
			case 'o':
				if ('-' == optarg[0])
				{
					printf ("Option -%c requires an argument.\n", c);
					exit (0);
				}
				strcpy (strOutName, optarg);
				break;
			case '?':
				if ('i' == optopt || 'o' == optopt)
					;
				else if (optopt == '?')
					;
				else if (isprint (optopt))
					fprintf (stderr, "Unknown option `-%c'.\n", optopt);
				else
					fprintf (stderr,
							"Unknown option character `\\x%x'.\n",
							optopt);
				fprintf (stdout, "Narc文件打包工具\n");
				fprintf (stdout, "%s [-i 需打包的文件所在的文件夹的名称] [-o 输出文件名]\n", argv[0]);
				return 1;
			default:
				abort ();
		}

	fpPak = fopen (strOutName, "wb+");
	if (fpPak == NULL)
	{
		printf ("Can't create \"%s\" file\n", strOutName);
		return 1;
	}



#ifdef PAK_NAME_DEBUG
	if (NULL == (fpPakNameTxt = fopen ("PakName.txt", "w+")))
	{
		printf ("Can't create \"PakName.txt\" file.\n");
		exit (0);
	}
#endif


	//进入文件夹
	if(_chdir( strPakDir ) )
	{
		switch (errno)
		{
			case ENOENT:
				printf( "Unable to locate the directory: %s\n", strPakDir );
				break;
			case EINVAL:
				printf( "Invalid buffer.\n");
				break;
			default:
				printf( "Unknown error.\n");
		}
		exit (0);
	}
	//到这里进入文件夹就成功了

	//获取bin文件的句柄

	if( (hFile = _findfirst( "*.bin", &c_file )) == -1L )
	{
		printf( "No *.bin files in current directory!\n" );
	}
	else
	{
		ulPakCount = 0;
		do
		{
			strcpy (strPakName[ulPakCount], c_file.name);
			tPakInfo [ulPakCount].ulLength = c_file.size;
			tPakInfo [ulPakCount].ulOffsetBegin = (0 != ulPakCount)?
				((4 - (tPakInfo[ulPakCount - 1].ulOffsetEnd % 4)) % 4 + tPakInfo[ulPakCount -1].ulOffsetEnd)
				:0;
			tPakInfo [ulPakCount].ulOffsetEnd = c_file.size + tPakInfo[ulPakCount].ulOffsetBegin;

			ulPakCount ++;
		}
		while( _findnext( hFile, &c_file ) == 0 );
		printf ("There are %d files\n", ulPakCount);
		_findclose( hFile );
	}

	ulPakLengthSum = tPakInfo[ulPakCount - 1].ulOffsetEnd + 0x8 + (4 - (tPakInfo[ulPakCount - 1].ulOffsetEnd % 4)) % 4;
	fileHeadHandle (fpPak, ulPakCount, tPakInfo);	
	fileHeadSecHandle (fpPak, strPakName, strOutName);
	fileHeadTrdHandle (fpPak, ulPakLengthSum);

	//将各个包写入需要打包的narc包中间
	for (iCount = 0; iCount < ulPakCount; iCount ++)
	{
#ifdef PAK_NAME_DEBUG
		fprintf (fpPakNameTxt, "%s\n", strPakName[iCount]);
		fprintf (fpPakNameTxt, "Offset begin on %0Xh.\n", tPakInfo[iCount].ulOffsetBegin);
		fprintf (fpPakNameTxt, "Offset end in %0Xh.\n", tPakInfo[iCount].ulOffsetEnd);
		fprintf (fpPakNameTxt, "Pak length = %0Xh.\n", tPakInfo[iCount].ulLength);
#endif
		fpSrc = fopen (strPakName[iCount], "rb");//需要打包的源文件
		if (fpSrc == NULL)
		{
			printf ("No \"%s\" file.\n", srcName);
			return 2;
		}

		dat = (BYTE *) malloc (sizeof (BYTE) * tPakInfo [iCount].ulLength);
		fread (dat, sizeof(BYTE), tPakInfo [iCount].ulLength, fpSrc);
		fwrite (dat, sizeof(BYTE), tPakInfo [iCount].ulLength, fpPak);
		switch ((tPakInfo[iCount].ulLength) % 4)
		{
			case 1:
				fputc (FILL_BYTE, fpPak);
			case 2:
				fputc (FILL_BYTE, fpPak);
			case 3:
				fputc (FILL_BYTE, fpPak);
			case 0:
				break;
			default:
				;
		}
		free (dat);
		fclose (fpSrc);

	}
#ifdef PAK_NAME_DEBUG
	fclose (fpPakNameTxt);
#endif
	ulOutLength = ftell (fpPak);
	fseek(fpPak, 8, SEEK_SET);
	fwrite (&ulOutLength, sizeof(ULONG), 1, fpPak);
	fclose (fpPak);
	printf("Repak successed.\n");
	return 0;
}
Пример #7
0
OBJECTDESC *ko_Nahraj_herni_prvky(void)
{
	char FileName[256];
	char Text[256];
	long error;
	int Count;
	int m;
	struct _finddata_t Data;
	long Done;

	GetPrivateProfileString("soundengine","sound_dir","c:\\",Directory,256,ini_file);
	GetPrivateProfileString("game","prvky_dir","c:\\",Directory3,256,ini_file);

	WaveFile = (WAVEFILEDESC *) malloc(1000 * sizeof(WAVEFILEDESC));
		if (WaveFile == NULL)
			MessageBox(NULL,"Nelze alokovat pamet pro WAVEFILEDESC","!!!",MB_OK);

	strcpy(FileName,Directory);
	strcat(FileName,"\\Index.dat");


	file = fopen(FileName,"r");
	if (file)
	{
		fgets(Text,30,file);
		NumOfFiles = atoi(Text);
		for (i=0; i<NumOfFiles; i++)
		{
			fgets(Text,30,file);
				Text[strlen(Text)-1] = '\0';
				strcpy(WaveFile[i].Name,Text);
			fgets(Text,30,file);
				WaveFile[i].Index = atoi(Text);
		}
	fclose(file);
	}
	else
		MessageBox(NULL,"Index.dat nenalezen","Nahraj herni prvky",MB_OK);

	Object = (OBJECTDESC *) malloc(NUMOFOBJECTS * sizeof(OBJECTDESC));
		if (Object == NULL)
			MessageBox(NULL,"Nelze alokovat pamet pro OBJECTDESC","!!!",MB_OK);

	for (i=0; i<NUMOFOBJECTS;i++)
		Object[i].Class = 0;

	SecondData = (SECONDDATADESC *) malloc(NUMOFOBJECTS * sizeof(SECONDDATADESC));
		if (SecondData == NULL)
			MessageBox(NULL,"Nelze alokovat pamet pro SECONDDATADESC","!!!",MB_OK);

	file = 0;

	strcpy(FileName,Directory3);
	strcat(FileName,"\\*.itm");

	Count = 0;
	Done = _findfirst(FileName,&Data);
	error = Done;

	while(error != -1)
	{
		Count++;
		error = _findnext(Done,&Data);
	}

	_findclose(Done);

	Done = _findfirst(FileName,&Data);
	error = Done;
	m=0;

if (error != -1)
{
	do
	{
		strcpy(FileName,Directory3);
		strcat(FileName,"\\");
		strcat(FileName,Data.name);
		file = fopen(FileName,"rb");
		if (file)
		{
			fread(Object+m,sizeof(OBJECTDESC),1,file);
			fseek(file,1000,SEEK_SET);
			fread(SecondData+m,sizeof(SECONDDATADESC),1,file);
			fclose(file);
		}
		else
			MessageBox(NULL,"Soubor nenalezen","Nahraj herni prvky",MB_OK);

			error = _findnext(Done,&Data);
		m++;
	}
	while(error != -1);
}
	_findclose(Done);

  return Object;
}
Пример #8
0
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;
}
Пример #9
0
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;
}
Пример #10
0
// 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;
}
Пример #11
0
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;
}
Пример #12
0
// 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;
}
Пример #13
0
//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	

}
Пример #14
0
/*
 * 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;
}
Пример #15
0
int CAvailabAsymmKeys::GetKeyList(CSortAsymKeyList& sortedAsymKeyList, unsigned nKeyType, int sortflag)
{
	// Erstellt eine sortierte Liste sortedAsymKeyList

	// durch den int Parameter 'sortflag' wird festgelegt nach welchen Kriterien die Liste sortiert wird:
	// BY_NAME
	// BY_FIRSTNAME
	// BY_KEYTYPE
	// BY_CREATTIME
	// BY_PERS_KEYID

	// nKeyType gibt an, welche Schlüsselbezeichner in die Liste aufgenommen werden:
	// nKeyType == ASYM_KEY : alle (EC, RSA, DSA)
	// nKeyType == EC_KEY  : nur EC
	// nKeyType == RSA_KEY : nur RSA
	// nKeyType == DSA_KEY : nur DSA
	// nKeyType == RSA_KEY | EC_KEY  : RSA und EC
	// usw.

	CAsymmKeyAttrib userfile(sortflag);

	sortedAsymKeyList.RemoveAll(); // Liste neu anlegen
	if ( (nKeyType == 0) || (nKeyType > 7) )
	{
		// nKeyType hat ungültige Werte
		return -1; // sortedAsymKeyList ist eine leere Liste
	}

	// ermittele die zur Verfügung stehenden Schlüssel(-bezeichner)

	long filehandle;
	int pos;
	int ret;
	struct _finddata_t fileinfo;
	CKeyFile KeyfileName;
	char *ctstr = NULL;
	char *creatime = NULL;
	char *name = NULL;
	char *firstname = NULL;
	char *keyType = NULL;
	char *keyID = NULL;

	CString key_identifier;
	
	// ermittele die Dateien, die in PseVerzeichnis liegen

	CString filename=(CString)PseVerzeichnis+((CString)"/*.*");		
	LPTSTR help1 = new TCHAR[filename.GetLength()+1];
	_tcscpy(help1, filename);
	char *filename2=help1;

	filehandle = _findfirst(filename2, &fileinfo);
	if (filehandle != -1)
	{
		// es gibt mindestens eine Datei im Verzeichnis PseVerzeichnis

		userfile.UserKeyfileName = (CString) fileinfo.name;
		key_identifier = (CString) fileinfo.name;

		pos = key_identifier.Find(PSE_FILE_SUFFIX);
		if (pos != -1)
		{
			// key_identifier sind von der Form "xxxx.PSE_FILE_SUFFIX"
			key_identifier = key_identifier.Left(pos); // entferne PSE_FILE_SUFFIX
#ifndef _UNSTABLE
			ret = KeyfileName.ExtractData(key_identifier, &ctstr, &creatime, &name, &firstname, &keyType, &keyID);// Speicherfreigabe!
#endif
			// Zuweisen der Werte
			userfile.UTCstring = (CString) ctstr; // Time in seconds since UTC 1/1/70
			userfile.CreatTime = (CString) creatime; // Date and time of creation
			userfile.Name = (CString) name; // Name of owner
			userfile.Firstname = (CString) firstname; // Firstname of owner
			userfile.KeyType = (CString) keyType; // Key Type {EC-xxx, RSA-xxx, DSA-xxx}
			userfile.PersKeyInfo = (CString) keyID; // Prrsönliche Schlüsselkennung des Schlüsselerzeugers
			
			// Für Definitionen EC_KEYFILE_IDSTRING, RSA_KEYFILE_IDSTRING, DSA_KEYFILE_IDSTRING siehe DlgAsymKeyCreat.h
			if (nKeyType == ASYM_KEY)
			{
				// alle verfügbaren Schlüssel einfügen

				sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
			}
			else
			{
				// Kombination von verschiedenen Schlüsseltypen möglich

				if ((nKeyType & EC_KEY) == EC_KEY)
				{
					if (userfile.KeyType.Find(EC_KEYFILE_IDSTRING) > -1)
						sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
				}
				if ((nKeyType & RSA_KEY) == RSA_KEY)
				{
					if (userfile.KeyType.Find(RSA_KEYFILE_IDSTRING) > -1)
						sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
				}
				if ((nKeyType & DSA_KEY) == DSA_KEY)
				{
					if (userfile.KeyType.Find(DSA_KEYFILE_IDSTRING) > -1)
						sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
				}
			}

			if (ctstr != NULL){ delete ctstr; ctstr = NULL; }
			if (creatime != NULL){ delete creatime;creatime = NULL; }
			if (name != NULL){ delete name;name = NULL; }
			if (firstname != NULL){ delete firstname;firstname = NULL; }
			if (keyType != NULL){ delete keyType;keyType = NULL; }
			if (keyID != NULL){ delete keyID;keyID = NULL; }
		}
		while(_findnext(filehandle, &fileinfo) == 0)
		{
			// es gibt mindestens noch eine weitere Datei im Verzeichnis PseVerzeichnis

			userfile.UserKeyfileName = (CString) fileinfo.name;
			key_identifier = (CString) fileinfo.name;

			pos = key_identifier.Find(PSE_FILE_SUFFIX);
			if (pos != -1)
			{
				// key_identifier sind von der Form "xxxx.PSE_FILE_SUFFIX"
				key_identifier = key_identifier.Left(pos); // entferne PSE_FILE_SUFFIX
#ifndef _UNSTABLE
				ret = KeyfileName.ExtractData(key_identifier, &ctstr, &creatime, &name, &firstname, &keyType, &keyID);// Speicherfreigabe!
#endif
				// Zuweisen der Werte
				userfile.UTCstring = (CString) ctstr; // Time in seconds since UTC 1/1/70
				userfile.CreatTime = (CString) creatime; // Date and time of creation
				userfile.Name = (CString) name; // Name of owner
				userfile.Firstname = (CString) firstname; // Firstname of owner
				userfile.KeyType = (CString) keyType; // Key Type {EC-xxx, RSA-xxx, DSA-xxx}
				userfile.PersKeyInfo = (CString) keyID; // Prrsönliche Schlüsselkennung des Schlüsselerzeugers

				// Für Definitionen EC_KEYFILE_IDSTRING, RSA_KEYFILE_IDSTRING, DSA_KEYFILE_IDSTRING siehe DlgAsymKeyCreat.h
				if (nKeyType == ASYM_KEY)
				{
					// alle verfügbaren Schlüssel einfügen

					sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
				}
				else
				{
					// Kombination von verschiedenen Schlüsseltypen möglich

					if ((nKeyType & EC_KEY) == EC_KEY)
					{
						if (userfile.KeyType.Find(EC_KEYFILE_IDSTRING) > -1)
							sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
					}
					if ((nKeyType & RSA_KEY) == RSA_KEY)
					{
						if (userfile.KeyType.Find(RSA_KEYFILE_IDSTRING) > -1)
							sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
					}
					if ((nKeyType & DSA_KEY) == DSA_KEY)
					{
						if (userfile.KeyType.Find(DSA_KEYFILE_IDSTRING) > -1)
							sortedAsymKeyList.AddTail(userfile); // Objekt in Liste einfügen
					}
				}
				if (ctstr != NULL){ delete ctstr; ctstr = NULL; }
				if (creatime != NULL){ delete creatime;creatime = NULL; }
				if (name != NULL){ delete name;name = NULL; }
				if (firstname != NULL){ delete firstname;firstname = NULL; }
				if (keyType != NULL){ delete keyType;keyType = NULL; }
				if (keyID != NULL){ delete keyID;keyID = NULL; }
			}
		}
		_findclose(filehandle);
	}
	return 0;
}
Пример #16
0
/*
* Function
*	windowsModLoadDir
*
* Description
*	Load the modules contained in a directory
*
* Parameters
*	dir	directory to search (relative)
*	modlist	list of module description structure
*
* Return
*	>=0	number of modules loaded
*	-1	error
*
* Remarks
*	
*/
static int windowsModLoadDir(unsigned int gfid, char *dir, tModList **modlist)
{
	tfModInfo	fModInfo;	/* init function of the modules */
	char	dname[256];	/* name of the funtions */
	char	sopath[256];	/* path of the lib[x].so */
	HMODULE	handle;		/* */
	int		modnb;		/* number on loaded modules */
	tModList	*curMod;
	tModList	*cMod;
	int		prio;
    
	modnb = 0;
	curMod = (tModList*)calloc(1, sizeof(tModList));

    // parcours du r�pertoire
	_finddata_t FData;
	char Dir_name[ 1024 ];
	sprintf( Dir_name, "%s\\*.dll", dir );
	long Dirent = _findfirst( Dir_name, &FData );
	if ( Dirent != -1 )
		do {
		sprintf(sopath, "%s\\%s", dir, FData.name);
		handle = LoadLibrary( sopath );
		if (handle != NULL) {
			if ((fModInfo = (tfModInfo)GetProcAddress(handle, dname)) != NULL) {
				/* DLL loaded, init function exists, call it... */
				if ((fModInfo(curMod->modInfo) == 0) && (curMod->modInfo[0].gfId == gfid)) {
					GfOut(">>> %s loaded >>>\n", sopath);
					modnb++;
					curMod->handle = handle;
					curMod->sopath = strdup(sopath);
					/* add the module in the list */
					if (*modlist == NULL) {
						*modlist = curMod;
						curMod->next = curMod;
					} else {
						/* sort by prio */
						prio = curMod->modInfo[0].prio;
						if (prio >= (*modlist)->modInfo[0].prio) {
							curMod->next = (*modlist)->next;
							(*modlist)->next = curMod;
							*modlist = curMod;
						} else {
							cMod = *modlist;
							do {
								if (prio < cMod->next->modInfo[0].prio) {
									curMod->next = cMod->next;
									cMod->next = curMod;
									break;
								}
								cMod = cMod->next;
							} while (cMod != *modlist);
						}
					}
					curMod = (tModList*)calloc(1, sizeof(tModList));
				} else {
					FreeLibrary(handle);
					GfTrace("windowsModLoadDir: Module: %s not retained\n", dname);
				}
			} else {
				GfTrace("windowsModLoadDir: ...  can't find proc %s\n", dname);
				FreeLibrary(handle);
				_findclose( Dirent );
				return -1;
			}
		}
		} while ( _findnext( Dirent, &FData ) != -1 );

		_findclose( Dirent );

		free(curMod);
		return modnb;
}
RRESULT OnCreate(void *pParam)
{
	/*
	//	Walk through in debug to trace all routes
	*/
	g_App.PreCheckArguments();

	sprintf( cstrReleaseDate, "Version : %s", ZGetSVNRevision().c_str()); //Possibly
	cclog(cstrReleaseDate); cclog("\n");

	g_DInput.Create(g_hWnd, FALSE, FALSE);
	g_pInput = new ZInput(&g_DInput);
	RSetGammaRamp(Z_VIDEO_GAMMA_VALUE);
	RSetRenderFlags(RRENDER_CLEAR_BACKBUFFER);

	ZGetInitialLoading()->Initialize(  1, 0, 0, RGetScreenWidth(), RGetScreenHeight(), 0, 0, 1024, 768 );

	cclog("InitialLoading success.\n");

	struct _finddata_t c_file;
	intptr_t hFile;
	char szFileName[256];
	#define FONT_DIR	"Font/"
	#define FONT_EXT	"ttf"
	if( (hFile = _findfirst(FONT_DIR"*."FONT_EXT, &c_file )) != -1L ){
		do{
			strcpy(szFileName, FONT_DIR);
			strcat(szFileName, c_file.name);
			AddFontResource(szFileName);
		}while( _findnext( hFile, &c_file ) == 0 );
		_findclose(hFile);
	}

	g_pDefFont = new CCFontR2;

	if( !g_pDefFont->Create("Default", Z_LOCALE_DEFAULT_FONT, DEFAULT_FONT_HEIGHT, 1.0f) )	{
		cclog("Fail to Create default font : CCFontR2 / main.cpp.. onCreate\n" );
		g_pDefFont->Destroy();
		SAFE_DELETE( g_pDefFont );
		g_pDefFont	= NULL;
	}
	g_pDC = new CCDrawContextR2(RGetDevice());

	if( ZGetInitialLoading()->IsUseEnable() )
	{
		ZGetInitialLoading()->AddBitmap( 0, "Interface/Default/LOADING/loading_adult.jpg" );
		ZGetInitialLoading()->AddBitmapBar( "Interface/Default/LOADING/loading.bmp" );
		ZGetInitialLoading()->SetText( g_pDefFont, 5, 5, cstrReleaseDate );
		ZGetInitialLoading()->AddBitmapGrade( "Interface/Default/LOADING/loading_grade_fifteen.jpg" );
		ZGetInitialLoading()->SetPercentage( 0.0f );
		ZGetInitialLoading()->Draw( MODE_FADEIN, 0 , true );
	}


	g_Core.Initialize(800, 600, g_pDC, g_pDefFont);
	Core::GetInstance()->SetHWND(RealSpace2::g_hWnd);

	cclog("interface Initialize success\n");

	ZLoadingProgress appLoading("application");
	if(!g_App.OnCreate(&appLoading))
	{
		ZGetInitialLoading()->Release();
		return R_ERROR_LOADING;
	}

	ZGetSoundEngine()->SetEffectVolume(Z_AUDIO_EFFECT_VOLUME);
	ZGetSoundEngine()->SetMusicVolume(Z_AUDIO_BGM_VOLUME);
	ZGetSoundEngine()->SetEffectMute(Z_AUDIO_EFFECT_MUTE);
	ZGetSoundEngine()->SetMusicMute(Z_AUDIO_BGM_MUTE);

	g_Core.SetWorkspaceSize(g_ModeParams.nWidth, g_ModeParams.nHeight);
	g_Core.GetMainFrame()->SetSize(g_ModeParams.nWidth, g_ModeParams.nHeight);
	ZGetOptionInterface()->Resize(g_ModeParams.nWidth, g_ModeParams.nHeight);

	// Default Key
	for(int i=0; i<ZACTION_COUNT; i++){
		ZACTIONKEYDESCRIPTION& keyDesc = ZGetConfiguration()->GetKeyboard()->ActionKeys[i];
		g_pInput->RegisterActionKey(i, keyDesc.nVirtualKey);
		if(keyDesc.nVirtualKeyAlt!=-1)
			g_pInput->RegisterActionKey(i, keyDesc.nVirtualKeyAlt);
	}

	g_App.SetInitialState();

//	ParseParameter(g_szCmdLine);

//	ZGetFlashBangEffect()->SetDrawCopyScreen(true);

	static const char *szDone = "Done.";
	ZGetInitialLoading()->SetLoadingStr(szDone);
	if( ZGetInitialLoading()->IsUseEnable() )
	{
#ifndef _FASTDEBUG
		ZGetInitialLoading()->SetPercentage( 100.f );
		ZGetInitialLoading()->Draw( MODE_FADEOUT, 0 ,true  );
#endif
		ZGetInitialLoading()->Release();
	}

	cclog("main : OnCreate() done\n");

	SetFocus(g_hWnd);

	return R_OK;
}
Пример #18
0
/*
* Function
*	windowsModInfoDir
*
* Description
*	Load the modules contained in a directory and retrieve info
*
* Parameters
*	dir	directory to search (relative)
*	modlist	list of module description structure
*
* Return
*	>=0	number of modules loaded
*	-1	error
*
* Remarks
*	
*/
static int windowsModInfoDir(unsigned int gfid, char *dir, int level, tModList **modlist)
{
	tfModInfo	fModInfo;	/* init function of the modules */
	char	dname[256];	/* name of the funtions */
	char	sopath[256];	/* path of the lib[x].so */
	HMODULE	handle;		/* */
	int		modnb;		/* number on loaded modules */
	tModList	*curMod;
	tModList	*cMod;
	int		prio;
    
	modnb = 0;
	curMod = (tModList*)calloc(1, sizeof(tModList));
    
	/* open the current directory */
	_finddata_t FData;

	char Dir_name[ 1024 ];
	sprintf( Dir_name, "%s\\*.*", dir );
	GfOut("trying dir info %s\n",dir);
	long Dirent = _findfirst( Dir_name, &FData );
	if ( Dirent != -1 ) {
		do {
			if (((strlen(FData.name) > 5) && 
						   (strcmp(".dll", FData.name+strlen(FData.name)-4) == 0)) || (level == 1)) { /* xxxx.dll */
				if (level == 1) {
					sprintf(sopath, "%s/%s/%s.dll", dir, FData.name, FData.name);
					strcpy(dname, FData.name);
				} else {
					sprintf(sopath, "%s/%s", dir, FData.name);
					strcpy(dname, FData.name);
					dname[strlen(dname) - 4] = 0; /* cut .dll */
				}
				handle = LoadLibrary( sopath );
				if (handle != NULL) {
					if ((fModInfo = (tfModInfo)GetProcAddress(handle, dname)) != NULL) {
						GfOut("Request Info for %s\n", sopath);
						/* DLL loaded, init function exists, call it... */
						if (fModInfo(curMod->modInfo) == 0) {
							modnb++;
							curMod->handle = NULL;
							curMod->sopath = strdup(sopath);
							/* add the module in the list */
							if (*modlist == NULL) {
								*modlist = curMod;
								curMod->next = curMod;
							} else {
								/* sort by prio */
								prio = curMod->modInfo[0].prio;
								if (prio >= (*modlist)->modInfo[0].prio) {
									curMod->next = (*modlist)->next;
									(*modlist)->next = curMod;
									*modlist = curMod;
								} else {
									cMod = *modlist;
									do {
										if (prio < cMod->next->modInfo[0].prio) {
											curMod->next = cMod->next;
											cMod->next = curMod;
											break;
										}
										cMod = cMod->next;
									} while (cMod != *modlist);
								}
							}
							FreeLibrary(handle);
							curMod = (tModList*)calloc(1, sizeof(tModList));
						} else {
							FreeLibrary(handle);
							GfTrace("windowsModInfoDir: Module: %s not retained\n", dname);
						}
					} else {
						GfTrace("windowsModInfoDir: ...  can't find proc %s\n", dname);
						FreeLibrary(handle);
					}
				} else {
					GfTrace("windowsModInfoDir: ...  can't open dll %s\n", sopath);
				}
						   }
		} while ( _findnext( Dirent, &FData ) != -1 );
	}
    
	_findclose( Dirent );
	free(curMod);
	return modnb;
}
Пример #19
0
/* gets the list of mechanisms */
int _sasl_load_plugins(const add_plugin_list_t *entrypoints,
		       const sasl_callback_t *getpath_cb,
		       const sasl_callback_t *verifyfile_cb)
{
    int result;
    char cur_dir[PATH_MAX], full_name[PATH_MAX+2], prefix[PATH_MAX+2];
				/* 1 for '\\' 1 for trailing '\0' */
    char * pattern;
    char c;
    int pos;
    const char *path=NULL;
    int position;
    const add_plugin_list_t *cur_ep;
    struct stat statbuf;		/* filesystem entry information */
    intptr_t fhandle;			/* file handle for _findnext function */
    struct _finddata_t finddata;	/* data returned by _findnext() */
    size_t prefix_len;

    if (! entrypoints
	|| ! getpath_cb
	|| getpath_cb->id != SASL_CB_GETPATH
	|| ! getpath_cb->proc
	|| ! verifyfile_cb
	|| verifyfile_cb->id != SASL_CB_VERIFYFILE
	|| ! verifyfile_cb->proc)
	return SASL_BADPARAM;

    /* get the path to the plugins */
    result = ((sasl_getpath_t *)(getpath_cb->proc))(getpath_cb->context,
						    &path);
    if (result != SASL_OK) return result;
    if (! path) return SASL_FAIL;

    if (strlen(path) >= PATH_MAX) { /* no you can't buffer overrun */
	return SASL_FAIL;
    }

    position=0;
    do {
	pos=0;
	do {
	    c=path[position];
	    position++;
	    cur_dir[pos]=c;
	    pos++;
	} while ((c!=PATHS_DELIMITER) && (c!=0));
	cur_dir[pos-1]='\0';


/* : check to make sure that a valid directory name was passed in */
	if (stat (cur_dir, &statbuf) < 0) {
	    continue;
	}
	if ((statbuf.st_mode & S_IFDIR) == 0) {
	    continue;
	}

	strcpy (prefix, cur_dir);
	prefix_len = strlen (prefix);

/* : Don't append trailing \ unless required */
	if (prefix[prefix_len-1] != '\\') {
	    strcat (prefix,"\\");
	    prefix_len++;
	}

	pattern = prefix;

/* : Check that we have enough space for "*.dll" */
	if ((prefix_len + DLL_MASK_LEN) > (sizeof(prefix) - 1)) {
	    _sasl_log(NULL, SASL_LOG_WARN, "plugin search mask is too big");
            continue;
	}

	strcat (prefix + prefix_len, "*" DLL_SUFFIX);

        fhandle = _findfirst (pattern, &finddata);
        if (fhandle == -1) {	/* no matching files */
            continue;
        }

/* : Truncate "*.dll" */
	prefix[prefix_len] = '\0';

	do {
	    size_t length;
	    void *library;
	    char *c;
	    char plugname[PATH_MAX];
	    int entries;

	    length = strlen(finddata.name);
	    if (length < 5) { /* At least <Ch>.dll */
		continue; /* can not possibly be what we're looking for */
	    }

/* : Check for overflow */
	    if (length + prefix_len >= PATH_MAX) continue; /* too big */

	    if (stricmp(finddata.name + (length - strlen(DLL_SUFFIX)), DLL_SUFFIX) != 0) {
		continue;
	    }

/* : Check that it is not a directory */
	    if ((finddata.attrib & _A_SUBDIR) == _A_SUBDIR) {
		continue;
	    }

/* : Construct full name from prefix and name */

	    strcpy (full_name, prefix);
	    strcat (full_name, finddata.name);
		
/* cut off .dll suffix -- this only need be approximate */
	    strcpy (plugname, finddata.name);
	    c = strrchr(plugname, '.');
	    if (c != NULL) *c = '\0';

	    result = _sasl_get_plugin (full_name, verifyfile_cb, &library);

	    if (result != SASL_OK) {
		continue;
	    }

	    entries = 0;
	    for (cur_ep = entrypoints; cur_ep->entryname; cur_ep++) {
		result = _sasl_plugin_load(plugname,
					   library,
					   cur_ep->entryname,
					   cur_ep->add_plugin);
		if (result == SASL_OK) {
		    ++entries;
		}
		/* If this fails, it's not the end of the world */
	    }
	    if (entries == 0) {
		_sasl_remove_last_plugin();
	    }

	} while (_findnext (fhandle, &finddata) == 0);
	
	_findclose (fhandle);

    } while ((c!='=') && (c!=0));

    return SASL_OK;
}
Пример #20
0
/* Main program */
int
main (int argc, char **argv)
{
  char *opt, *needle = NULL;
  int ret = 0;
  TCHAR lpMessage[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. */
	  LoadString( GetModuleHandle(NULL), IDS_NO_SUCH_FILE, (LPTSTR)lpMessage, 4096);
	  CharToOem(lpMessage, lpMessage);
	  fprintf (stderr, lpMessage, *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
	        {
	          LoadString(GetModuleHandle(NULL), IDS_CANNOT_OPEN, (LPTSTR)lpMessage, 4096);
	          CharToOem(lpMessage, lpMessage);
	          fprintf (stderr, lpMessage,
		           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) );
}
Пример #21
0
static void
chkparm (struct arginfo *arg, char *str)
{
  char tmpstr[MAX_PATH + 1];
  char *cp;
  char *pnt2;
  short remarg;
  long hFile;
  struct _finddata_t c_file;

  remarg = 0;
  if (*str == '!')
    {
      remarg = 1;
      ++str;
    }
  if (strchr (str, '?') || strchr (str, '*'))
    {
      if (remarg)
	{
	  removearg (arg, str);
	}
      else
	{
	  strcpy (tmpstr, str);
	  if (!(cp = strrchr (tmpstr, '\\')))
	    if (!(cp = strrchr (tmpstr, '/')))
	      if (!(cp = strrchr (tmpstr, ':')))
		cp = tmpstr - 1;
	  pnt2 = cp + 1;
	  hFile = _findfirst (str, &c_file);
	  while (hFile > 0)
	    {
	      if (!(c_file.attrib & _A_SUBDIR))
		{
		  cp = pnt2;
		  strcpy (pnt2, c_file.name);
		  while (*cp)
		    {
		      if (islower (*cp))
			{
			  strcpy (pnt2, c_file.name);
			  break;
			}
		      *cp = tolower (*cp);
		      ++cp;
		    }
		  addarg (arg, tmpstr);
		}
	      if (_findnext (hFile, &c_file))
		{
		  _findclose (hFile);
		  hFile = 0;
		}
	    }
	}
    }
  else
    {
      if (remarg)
	removearg (arg, str);
      else
	addarg (arg, str);
    }
}
Пример #22
0
X509 * InteropResolver::nextFile2Cert(void) {


	if (m_searchFinished)
		return NULL;

	int res;

	if (!m_searchStarted) {

		char * base = XMLString::transcode(mp_baseURI);
		safeBuffer path = base;
		XSEC_RELEASE_XMLCH(base);

		path.sbStrcatIn("/certs/*.crt");

#if defined(_WIN32)

		// Reverse the "backslash" characters

		reverseSlash(path);

		m_handle = (long) _findfirst(path.rawCharBuffer(), &m_finder);
		res = m_handle;
#else
		if (glob(path.rawCharBuffer(), 0, NULL, &m_globbuf) != 0)
			res = -1;
		else
			res = 0;
#endif

		m_searchStarted = true;

	}
	else {

#if defined(_WIN32)
		res = _findnext(m_handle, &m_finder);
#else
		if (m_fcount == (int) m_globbuf.gl_pathc)
			res = -1;
		else
			res = 0;
#endif

	}

	if (res == -1) {

		m_searchFinished = true;
		return NULL;

	}

	/* 
	 * Create the OpenSSL BIOs necessary to read in the X509 cert
	 */

	BIO * bioCert;
	if ((bioCert = BIO_new(BIO_s_file())) == NULL) {

		std::cerr << "Error opening certificate file\n\n";
		exit (1);

	}

	// Create the filename
	safeBuffer fname;
#if defined(_WIN32)
	fname.sbTranscodeIn(mp_baseURI);
	fname.sbStrcatIn("/certs/");
	fname.sbStrcatIn(m_finder.name);
	reverseSlash(fname);
#else
	fname.sbStrcpyIn(m_globbuf.gl_pathv[m_fcount++]);
#endif

	if (BIO_read_filename(bioCert, fname.rawCharBuffer()) <= 0) {

		std::cerr << "Error opening certificate file\n" << fname.rawCharBuffer() << std::endl;
		return NULL;

	}

	X509 * x509 = d2i_X509_bio(bioCert, NULL);
	BIO_free(bioCert);

	return x509;


}
Пример #23
0
FileList::FileList(const FilePath & filepath)
{
    DVASSERT(filepath.IsDirectoryPathname());
    
	path = filepath;

// Windows version
#if defined(__DAVAENGINE_WIN32__)

	//char tmp[_MAX_PATH];
	//_getcwd(tmp, _MAX_PATH);
	//Path = tmp;
	FilePath prevDir = FileSystem::Instance()->GetCurrentWorkingDirectory();
	BOOL res = SetCurrentDirectoryA(path.GetAbsolutePathname().c_str());

	if (res)
	{
		struct _finddata_t c_file;
		intptr_t hFile;
		FileEntry entry;

		if( (hFile = _findfirst( "*", &c_file )) != -1L )
		{
			do
			{
                //TODO: need to check for Win32
				entry.path = filepath + c_file.name;
				entry.name = c_file.name;
				entry.size = c_file.size;
				entry.isDirectory = (_A_SUBDIR & c_file.attrib) != 0;
				if(entry.isDirectory)
				{
					entry.path.MakeDirectoryPathname();
				}

				fileList.push_back(entry);
				//Logger::FrameworkDebug("filelist: %s %s", filepath.c_str(), entry.name.c_str());
			}
			while( _findnext( hFile, &c_file ) == 0 );

			_findclose( hFile );
		}
	}
	FileSystem::Instance()->SetCurrentWorkingDirectory(prevDir);

	//TODO add drives
	//entry.Name = "E:\\";
	//entry.isDirectory = true;
	//Files.push_back(entry);
#elif defined(__DAVAENGINE_MACOS__) || defined(__DAVAENGINE_IPHONE__)
	struct dirent **namelist;
	FileEntry entry;

	int32 n = scandir(path.GetAbsolutePathname().c_str(), &namelist, 0, alphasort);

	if (n >= 0)
	{
		while(n--)
		{
			entry.path = path + namelist[n]->d_name;
			entry.name = namelist[n]->d_name;
			entry.size = 0;
			entry.isDirectory = namelist[n]->d_type == DT_DIR;
            if(entry.isDirectory)
            {
                entry.path.MakeDirectoryPathname();
            }
			fileList.push_back(entry);
			free(namelist[n]);
		}
		free(namelist);
	}
#elif defined (__DAVAENGINE_ANDROID__)
	JniFileList jniFileList;
	Vector<JniFileList::JniFileListEntry> entrys = jniFileList.GetFileList(path.GetAbsoluteAssetPathnameTruncated());
	FileEntry entry;
	for (int32 i = 0; i < entrys.size(); ++i)
	{
		const JniFileList::JniFileListEntry& jniEntry = entrys[i];

		entry.path = path + jniEntry.name;
		entry.name = jniEntry.name;
		entry.size = jniEntry.size;
		entry.isDirectory = jniEntry.isDirectory;

		if(entry.isDirectory)
		{
			entry.path.MakeDirectoryPathname();
		}
		fileList.push_back(entry);
	}
#endif //PLATFORMS

	directoryCount = 0;
	fileCount = 0;
	for (int fi = 0; fi < GetCount(); ++fi)
	{
		if (IsDirectory(fi))
		{
			if (!IsNavigationDirectory(fi))
				directoryCount++;
		}else
			fileCount++;
	}
}
Пример #24
0
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);
}
Пример #25
0
/*!
* For a given path, this method lists all files, directories and
* sub-directories it contains and stores the filenames in the fileList vector.
*
* \param fileList list of files in folder
* \param path folder's path to list
* \param symLinks follow Unix links?
*
* \return path exists and is a directory
*/
bool CUtil::GetFileList(StringVector &fileList, const string &path, bool symLinks)
{
    string fullPath;
#ifdef UNIX
    DIR *dir;
    struct dirent *fileRead;
    struct stat inodeData;

    // opening the given path
    dir = opendir(path.c_str());

    // If the dir doesn't exist
    if (dir == NULL)
        return(false);

    // each file is processed until the last one
    while ((fileRead = readdir(dir)) != NULL)
    {
        // '.' & '..' are omitted
        if ((strcmp(fileRead->d_name, ".") != 0) && (strcmp(fileRead->d_name, "..") != 0))
        {
            // fullPath contains the path + the file name.
            fullPath = path + '/' + fileRead->d_name;
            if (symLinks)
            {
                if (stat(fullPath.c_str(), &inodeData) >= 0)
                {
                    // for each file, store the fullPath into the ofstream
                    if (!S_ISDIR(inodeData.st_mode))
                        fileList.push_back(fullPath);
                    else
                    {
                        // for each directory, its file list is obtained
                        GetFileList(fileList, fullPath, symLinks);
                    }
                }
            }
            else
            {
                if (lstat(fullPath.c_str(), &inodeData) >= 0)
                {
                    // for each file, store the fullPath into the ofstream
                    if (!S_ISLNK(inodeData.st_mode))
                    {
                        if (!S_ISDIR(inodeData.st_mode))
                            fileList.push_back(fullPath);
                        else
                        {
                            // for each directory, its file list is obtained
                            GetFileList(fileList, fullPath, symLinks);
                        }
                    }
                }
            }
        }
    }
    // close the directory
    closedir(dir);
#else
    struct _finddata_t c_file;
    ptrdiff_t hFile;
    string findPath = path + "\\*.*";

    // the first file is obtained
    hFile = _findfirst(findPath.c_str(), &c_file);

    // If the dir doesn't exist
    if (hFile == -1)
        return(false);

    // each file is processed until the last one
    while (_findnext(hFile, &c_file) == 0)
    {
        // for each file (not a directory (_A_SUBDIR), store its name into the fileList
        fullPath = path + "\\" + c_file.name;
        if (!(c_file.attrib & _A_SUBDIR))
            fileList.push_back(fullPath);
        else if ((strcmp(".", c_file.name) != 0) && (strcmp("..", c_file.name) != 0))
        {
            // for each directory, except '.' and '..', its file list is obtained
            GetFileList(fileList, fullPath, symLinks);
        }
    }
    // close the directory
    _findclose(hFile);
#endif
    return(true);
}
Пример #26
0
/*
==============
Sys_ListFilteredFiles
==============
*/
void Sys_ListFilteredFiles(const char *basedir, char *subdirs, char *filter, char **list, int *numfiles)
{
	char               search[MAX_OSPATH], newsubdirs[MAX_OSPATH];
	char               filename[MAX_OSPATH];
	intptr_t           findhandle;
	struct _finddata_t findinfo;

	if (*numfiles >= MAX_FOUND_FILES - 1)
	{
		return;
	}

	if (strlen(subdirs))
	{
		Com_sprintf(search, sizeof(search), "%s\\%s\\*", basedir, subdirs);
	}
	else
	{
		Com_sprintf(search, sizeof(search), "%s\\*", basedir);
	}

	findhandle = _findfirst(search, &findinfo);
	if (findhandle == -1)
	{
		return;
	}

	do
	{
		if (findinfo.attrib & _A_SUBDIR)
		{
			if (Q_stricmp(findinfo.name, ".") && Q_stricmp(findinfo.name, ".."))
			{
				if (strlen(subdirs))
				{
					Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s\\%s", subdirs, findinfo.name);
				}
				else
				{
					Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s", findinfo.name);
				}

				Sys_ListFilteredFiles(basedir, newsubdirs, filter, list, numfiles);
			}
		}
		if (*numfiles >= MAX_FOUND_FILES - 1)
		{
			break;
		}
		Com_sprintf(filename, sizeof(filename), "%s\\%s", subdirs, findinfo.name);
		if (!Com_FilterPath(filter, filename, qfalse))
		{
			continue;
		}

		list[*numfiles] = CopyString(filename);
		(*numfiles)++;
	}
	while (_findnext(findhandle, &findinfo) != -1);

	_findclose(findhandle);
}
Пример #27
0
bool get_filename_from_base(
	std::vector<std::string> &in_list,
	std::vector<std::string> &out_list,
	const std::string &path,
	const std::string &base_name,
	const char **filter )
{
#ifdef SFML_SYSTEM_WINDOWS
	std::string temp = path + base_name + "*";

	struct _finddata_t t;
	intptr_t srch = _findfirst( temp.c_str(), &t );

	if  ( srch < 0 )
		return false;

	do
	{
		const char *what = t.name;
		size_t what_len = strlen( what );

		if (( strcmp( what, "." ) != 0 )
				&& ( strcmp( what, ".." ) != 0 ))
		{
#else

	DIR *dir;
	struct dirent *ent;

	if ( (dir = opendir( path.c_str() )) == NULL )
		return false;

	while ((ent = readdir( dir )) != NULL )
	{
		const char *what = ent->d_name;
		size_t what_len = strlen( what );
		size_t base_len = base_name.size();

		if (( strcmp( what, "." ) != 0 )
				&& ( strcmp( what, ".." ) != 0 )
				&& ( what_len >= base_len )
				&& ( strncasecmp( what, base_name.c_str(), base_len ) == 0 ))
		{
#endif // SFML_SYSTEM_WINDOWS
			if ( filter )
			{
				bool add=false;
				int i=0;
				while ( filter[i] != NULL )
				{
					if ( c_tail_compare( what,
						what_len,
						filter[i],
						strlen( filter[i] ) ) )
					{
						add=true;
						break;
					}
					i++;
				}

				if ( add )
					in_list.push_back( path + what );
				else
					out_list.push_back( path + what );
			}
			else
				in_list.push_back( path + what );
#ifdef SFML_SYSTEM_WINDOWS
		}
	} while ( _findnext( srch, &t ) == 0 );
	_findclose( srch );
#else
		}
	}
	closedir( dir );
#endif // SFML_SYSTEM_WINDOWS

	return !(in_list.empty());
}
Пример #28
0
void loadsavescreen_delete( void )
{
	GameInfo	*gameInfo = g_loadsaveWindow->GetGameInfo();

	Assert(gameInfo);
	if (!gameInfo) return;

//	Assert(saveInfo);
//	if (!saveInfo) return;

	SaveInfo	*saveInfo = g_loadsaveWindow->GetSaveInfo();
	if(saveInfo)
	{
		MBCHAR		path[_MAX_PATH];

		sprintf(path, "%s%s%s", gameInfo->path, FILE_SEP, saveInfo->fileName);

#ifdef WIN32
		if ( DeleteFile( path ) )
#elif defined(HAVE_UNISTD_H)
		if ( !unlink( path ) )
#endif
		{
			// FIXME ? Do we want to worry about deleting .gw files?

			// Refill list two.
			sint32 one = g_loadsaveWindow->GetListOne()->GetSelectedItemIndex();
			sint32 two = g_loadsaveWindow->GetListTwo()->GetSelectedItemIndex();

			g_loadsaveWindow->SetType( g_loadsaveWindow->GetType() );

			g_loadsaveWindow->GetListOne()->SelectItem( one );

			if ( two && two == g_loadsaveWindow->GetListTwo()->NumItems() ) --two;
			g_loadsaveWindow->GetListTwo()->SelectItem( two );

	// This wasn't working.
	//  		aui_Item *item = g_loadsaveWindow->GetListTwo()->GetSelectedItem();
	//  		if ( item )
	//  		{
	//  			g_loadsaveWindow->GetListTwo()->RemoveItem( item->Id() );
	//  			delete item;
	//  		}
		}
		else
		{
			Assert( "Couldn't delete file." == 0 );
		}
	}
	else
	{
#ifdef WIN32
		MBCHAR		path[_MAX_PATH];
		sprintf(path, "%s%s*.*", gameInfo->path, FILE_SEP);

		_finddata_t findData;
		int fileHandle=_findfirst(path,&findData);
		while(fileHandle)
		{
			sprintf(path, "%s%s%s", gameInfo->path, FILE_SEP, findData.name);
			DeleteFile(path);
			if(_findnext(fileHandle,&findData))
			{
				_findclose(fileHandle);
				fileHandle=0;
			}
		}
		sprintf(path, "%s", gameInfo->path);
		int retval=_rmdir(path);
		assert(!retval);
		g_loadsaveWindow->FillListTwo(NULL);
		g_loadsaveWindow->SetType(g_loadsaveWindow->GetType());
#endif // WIN32
	}
}
Пример #29
0
nfsstat3 CNFS3Prog::ProcedureREADDIR(void)
{
    char *path;
    cookie3 cookie;
    cookieverf3 cookieverf;
    count3 count;
    post_op_attr dir_attributes;
    fileid3 fileid;
    filename3 name;
    bool eof;
    bool bFollows;
    nfsstat3 stat;
    char filePath[MAXPATHLEN];
    int handle;
    struct _finddata_t fileinfo;

    PrintLog("READDIR");
    path = GetPath();
    Read(&cookie);
    Read(&cookieverf);
    Read(&count);
    stat = CheckFile(path);

    if (stat == NFS3_OK) {
        dir_attributes.attributes_follow = GetFileAttributesForNFS(path, &dir_attributes.attributes);

        if (!dir_attributes.attributes_follow) {
            stat = NFS3ERR_IO;
        }    
    }

    Write(&stat);
    Write(&dir_attributes);

    if (stat == NFS3_OK) {
        Write(&cookieverf);
        sprintf_s(filePath, "%s\\*", path);
        cookie = 0;
        eof = false;
        handle = _findfirst(filePath, &fileinfo);
        bFollows = true;

        if (handle) {
            do {
                Write(&bFollows); //value follows
                sprintf_s(filePath, "%s\\%s", path, fileinfo.name);
                fileid = GetFileID(filePath);
                Write(&fileid); //file id
                name.Set(fileinfo.name);
                Write(&name); //name
                ++cookie;
                Write(&cookie); //cookie
            } while (_findnext(handle, &fileinfo) == 0);

            _findclose(handle);
        }

        bFollows = false;
        Write(&bFollows);
        eof = true;
        Write(&eof); //eof
    }

    return stat;
}
Пример #30
0
char *
AcpiOsGetNextFilename (
    void                    *DirHandle)
{
    EXTERNAL_FIND_INFO      *SearchInfo = DirHandle;
    int                     Status;
    char                    FileTypeNotMatched = 1;


    /*
     * Loop while we have matched files but not found any files of
     * the requested type.
     */
    while (FileTypeNotMatched)
    {
        /* On the first call, we already have the first match */

        if (SearchInfo->State == 0)
        {
            /* No longer the first match */

            SearchInfo->State = 1;
        }
        else
        {
            /* Get the next match */

            Status = _findnext (SearchInfo->FindHandle, &SearchInfo->DosInfo);
            if (Status != 0)
            {
                return (NULL);
            }
        }

        /*
         * Found a match, now check to make sure that the file type
         * matches the requested file type (directory or normal file)
         *
         * NOTE: use of the attrib field saves us from doing a very
         * expensive stat() on the file!
         */
        switch (SearchInfo->RequestedFileType)
        {
        case REQUEST_FILE_ONLY:

            /* Anything other than A_SUBDIR is OK */

            if (!(SearchInfo->DosInfo.attrib & _A_SUBDIR))
            {
                FileTypeNotMatched = 0;
            }
            break;

        case REQUEST_DIR_ONLY:

            /* Must have A_SUBDIR bit set */

            if (SearchInfo->DosInfo.attrib & _A_SUBDIR)
            {
                FileTypeNotMatched = 0;
            }
            break;

        default:

            return (NULL);
        }
    }

    return (SearchInfo->DosInfo.name);
}