/**
*           bIndex == 1     遍历指定文件夹并解压缩
*           数据升级Config因为包括黑白名单缓存,需特殊处理
*/
void CDownloadOperation::uncompressTraverse(IN LPWSTR path ,IN BYTE bIndex, IN OUT LPWSTR parentDirectory )
{
	USES_CONVERSION;
	WIN32_FIND_DATAW  fw;
	HANDLE hFind= FindFirstFileW(path,&fw);

	if(hFind == INVALID_HANDLE_VALUE)
		return ;

	WBRETURN bIsWBCab = NONE;

	do
	{
		if(wcscmp(fw.cFileName,L".") == 0 || wcscmp(fw.cFileName,L"..") == 0 || wcscmp(fw.cFileName,L".svn") == 0)
			continue;

		if(fw.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if(bIndex == 1)
			{	

			}
		}
		else
		{
			if(bIndex == 1 && strstr(W2A(fw.cFileName),"cab") != NULL)
			{
				std::wstring newFile ;
				bool bIsSC = isSpecialCab(fw.cFileName);

				newFile = this->getAppDataPath();

				if( !bIsSC )
					newFile += BANKINFOPATHNOFIND;

				WBRETURN bWBCab = IsNewTBCacheFile(fw.cFileName);
				if( bWBCab != NONE)
					if( bWBCab != bIsWBCab && bIsWBCab != ALL )
					{
						if( bIsWBCab == NONE)
							bIsWBCab = bWBCab;
						else
							bIsWBCab = ALL;
					}
				

				std::wstring existingFile ;
				existingFile = getBankCachePath();
				existingFile += fw.cFileName;

				//没有通过验证的升级包不允许升级
				if( _UpdateMgr.isSafeFile((wchar_t *)existingFile.c_str() ) )
				{				
					moveFiles(fw.cFileName, true);	

					CCabExtract tt;
					if(tt.ExtractFile(existingFile.c_str(), newFile.c_str() ) )
						OutputDebugStringW(L"extractFile is OK!");
					else
					{
						moveFiles(fw.cFileName, false);
					}
				}
			}
		}
	}
	while( FindNextFile(hFind,&fw) );  

	this->UpdateWBFile(bIsWBCab);
	FindClose(hFind);
}
Exemple #2
0
BOOL CALLBACK dialogproc(HWND h,UINT m,WPARAM w,LPARAM l)
{
	switch (m) {
		case WM_COMMAND:
			switch (LOWORD(w)) {
				case IDCANCEL:
					DestroyWindow(h);
					break;
				case 10:
					{
						char file[MAX_PATH]="";
						ofn.lpstrFile=file;
						ofn.nMaxFile=MAX_PATH;
						if (GetOpenFileName(&ofn)) {
							BASS_StreamFree(chan); // free the old stream
							if (!(chan=BASS_StreamCreateFile(FALSE,file,0,0,BASS_SAMPLE_LOOP))) {
								// it ain't playable
								MESS(10,WM_SETTEXT,0,"click here to open a file...");
								MESS(11,WM_SETTEXT,0,"");
								Error("Can't play the file");
								break;
							}
							MESS(10,WM_SETTEXT,0,file);
							{ // display the file type and length
								QWORD bytes=BASS_ChannelGetLength(chan,BASS_POS_BYTE);
								DWORD time=BASS_ChannelBytes2Seconds(chan,bytes);
								BASS_CHANNELINFO info;
								BASS_ChannelGetInfo(chan,&info);
								sprintf(file,"channel type = %x (%s)\nlength = %I64u (%u:%02u)",
									info.ctype,GetCTypeString(info.ctype,info.plugin),bytes,time/60,time%60);
								MESS(11,WM_SETTEXT,0,file);
								MESS(12,TBM_SETRANGE,1,MAKELONG(0,time)); // update scroller range
							}
							BASS_ChannelPlay(chan,FALSE);
						}
					}
					break;
			}
			break;

		case WM_HSCROLL:
			if (l && LOWORD(w)!=SB_THUMBPOSITION && LOWORD(w)!=SB_ENDSCROLL) { // set the position
				int pos=SendMessage((HWND)l,TBM_GETPOS,0,0);
				BASS_ChannelSetPosition(chan,BASS_ChannelSeconds2Bytes(chan,pos),BASS_POS_BYTE);
			}
			break;

		case WM_TIMER:
			MESS(12,TBM_SETPOS,1,(DWORD)BASS_ChannelBytes2Seconds(chan,BASS_ChannelGetPosition(chan,BASS_POS_BYTE))); // update position
			break;

		case WM_INITDIALOG:
			win=h;
			// initialize default output device
			if (!BASS_Init(-1,44100,0,win,NULL)) {
				Error("Can't initialize device");
				DestroyWindow(win);
				break;
			}
			// initialize file selector
			memset(&ofn,0,sizeof(ofn));
			ofn.lStructSize=sizeof(ofn);
			ofn.hwndOwner=h;
			ofn.Flags=OFN_HIDEREADONLY|OFN_EXPLORER;
			ofn.lpstrFilter=filter;
			memcpy(filter,"BASS built-in (*.mp3;*.mp2;*.mp1;*.ogg;*.wav;*.aif)\0*.mp3;*.mp2;*.mp1;*.ogg;*.wav;*.aif\0",88);
			{ // look for plugins (in the executable's directory)
				WIN32_FIND_DATA fd;
				HANDLE fh;
				char path[MAX_PATH],*fp=filter+88;
				GetModuleFileName(0,path,sizeof(path));
				strcpy(strrchr(path,'\\')+1,"bass*.dll");
				fh=FindFirstFile(path,&fd);
				if (fh!=INVALID_HANDLE_VALUE) {
					do {
						HPLUGIN plug;
						if (plug=BASS_PluginLoad(fd.cFileName,0)) { // plugin loaded...
							const BASS_PLUGININFO *pinfo=BASS_PluginGetInfo(plug); // get plugin info to add to the file selector filter...
							int a;
							for (a=0;a<pinfo->formatc;a++) {
								fp+=sprintf(fp,"%s (%s) - %s",pinfo->formats[a].name,pinfo->formats[a].exts,fd.cFileName)+1; // format description
								fp+=sprintf(fp,"%s",pinfo->formats[a].exts)+1; // extension filter
							}
							// add plugin to the list
							MESS(20,LB_ADDSTRING,0,fd.cFileName);
						}
					} while (FindNextFile(fh,&fd));
					FindClose(fh);
				}
				if (!MESS(20,LB_GETCOUNT,0,0)) // no plugins...
					MESS(20,LB_ADDSTRING,0,"no plugins - visit the BASS webpage to get some");
				memcpy(fp,"All files\0*.*\0\0",15);
			}
			SetTimer(h,0,500,0); // timer to update the position
			return 1;

		case WM_DESTROY:
			// "free" the output device and all plugins
			BASS_Free();
			BASS_PluginFree(0);
			break;
	}
	return 0;
}
Exemple #3
0
void RecursiveHandler(const char* startdir, const char* outputdir, char* command, int option )
{
	WIN32_FIND_DATA	findData;
	HANDLE			findHandle;
	CString			startdirDyn;

	startdirDyn		= startdir;
	startdirDyn		+= "\\*.*";
	findHandle		= FindFirstFile(LPCTSTR(startdirDyn), &findData );

	DEBUG_EXEC(printf("\ndir: %s", LPCTSTR(startdirDyn)));
	if( INVALID_HANDLE_VALUE != findHandle )
	{
		int count = 0;
		do
		{
			if( count > 1 )
			{
				CString	 subDirDyn;
				subDirDyn = startdir;
				subDirDyn += "\\";
				subDirDyn += findData.cFileName;
				CString	 outputDirDyn;
				outputDirDyn  = outputdir;
				outputDirDyn += "\\";
				outputDirDyn += subDirDyn;

				if( findData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY )
				{
					DEBUG_EXEC(printf("\ndir:	"));
					DEBUG_EXEC(printf("(%s)", findData.cFileName ));
					_mkdir(LPCTSTR(outputDirDyn)); DEBUG_EXEC(printf("\nmkdir: %s", LPCTSTR(outputDirDyn)));
					RecursiveHandler(LPCTSTR(subDirDyn), outputdir, command, option);

				}
				else
				{
					DEBUG_EXEC(printf("\nprocess: "));
					CString	 fileNameDyn;
					fileNameDyn = startdir;
					fileNameDyn += "\\";
					fileNameDyn += findData.cFileName;
					DEBUG_EXEC(printf("%s -> %s", LPCTSTR(fileNameDyn), LPCTSTR(outputDirDyn) ));
					char buffer[1024];
					switch(option)
					{
					case R_QUANTIZE:
						sprintf(buffer, "%s -q %s %s", command, LPCTSTR(fileNameDyn), LPCTSTR(outputDirDyn)  );
						DEBUG_EXEC(printf("\n%s",buffer));
						system(buffer);
						break;
					case R_QUANTIZE_ALL:
						sprintf(buffer, "%s -qa %s %s", command, LPCTSTR(fileNameDyn), LPCTSTR(outputDirDyn)  );
						DEBUG_EXEC(printf("\n%s",buffer));
						system(buffer);
						break;
					case R_DTX2TGA:
						char tempBuf[256], tempBuf2[256];
						memset(tempBuf, '\0', 256);
						memset(tempBuf2, '\0', 256);
						strncpy(tempBuf, fileNameDyn, strlen(fileNameDyn)-3);
						// printf("\n\n\n%s\n\n", tempBuf);
						sprintf(tempBuf2, "%stga", tempBuf);
						// printf("\n\n%s\n\n\n", tempBuf2);
						sprintf(buffer, "%s -dtx2tga %s %s", command, LPCTSTR(fileNameDyn), LPCTSTR(tempBuf2));
						DEBUG_EXEC(printf("\n%s",buffer));
						system(buffer);
						break;
					};
					// QuantizeAllhandler(LPCTSTR(fileNameDyn), LPCTSTR(outputDirDyn) );
				}
			}
			count++;
		} while( FindNextFile(findHandle,&findData ) );

		FindClose(findHandle);
	}
}
Exemple #4
0
int main (int argc, char* argv[]) {

	if (argc < 2) {
		printf("Usage:\n");
		printf("%s max_filename [manager [port]]\n",argv[0]);
		return 1;
	}

	//-- Come up with a temporary path for creating archives
	if (!ExpandEnvironmentStrings("%TEMP%",work_path,MAX_PATH)) {
		if (!ExpandEnvironmentStrings("%TMP%",work_path,MAX_PATH)) {
			if (!ExpandEnvironmentStrings("%HOMEPATH%",work_path,MAX_PATH))
				strcpy(work_path,"c:\\");
		}
	}

	if (work_path[strlen(work_path) - 1] != '\\')
		strcat(work_path,"\\");

	//-- Creates new manager access module instance
	MaxNetManager* manager = CreateManager();
	if (manager) {
		try {
			//-- Setup default manager port
			short port = DF_MGRPORT;
			//-- Placeholder for manager name
			char managername[MAX_PATH];
			//-- If we have a port defined, use it
			if (argc > 3)
				port = atoi(argv[3]);
			//-- If we have a host name (or ip address) for the manager, use it
			if (argc > 2)
				strcpy(managername,argv[2]);
			else {
				//-- Otherwise, find out who is the manager (if any)
				//   The API will broadcast a message looking for a
				//   manager using the given port. If a manager is
				//   found, its name/ip address will be placed in 
				//   "managername" below.
				if (!manager->FindManager(port,managername)) {
					printf("Could not find a Manager\n");
					DestroyManager(manager);
					return 1;
				}
			}
			//-- Connect to the manager
			manager->Connect(port,managername);
			//-- We're connected. Sumbmit Job(s)...
			WIN32_FIND_DATA find;
			HANDLE findhandle = FindFirstFile(argv[1],&find);
			if (findhandle != INVALID_HANDLE_VALUE) {
				char opath[MAX_PATH],npath[MAX_PATH];
				_splitpath(argv[1],opath,npath,0,0);
				strcat(opath,npath);
				if (opath[strlen(opath) - 1] != '\\')
					strcat(opath,"\\");
				do {
					strcpy(npath,opath);
					strcat(npath,find.cFileName);
					printf("Submitting %s...",find.cFileName);
					if (!assign_job(manager,npath))
						break;
					printf("\r%s Submitted successfully...\n",find.cFileName);
				} while (FindNextFile(findhandle,&find));
				FindClose(findhandle);
			}
			manager->Disconnect();
		//-- Exception Handler
		} catch (MaxNet* maxerr) {
			printf("\n%s (0x%08X)\n",maxerr->GetErrorText(),maxerr->GetError());
		}
		//-- Clean up manager instance
		DestroyManager(manager);
	}
	return 0;
}
Exemple #5
0
/**
   sys_read_dir : string -> string list
   <doc>Return the content of a directory</doc>
**/
Array<String> _hx_std_sys_read_dir( String p )
{
   Array<String> result = Array_obj<String>::__new();

#if defined(NEKO_WINDOWS)
   const wchar_t *path = p.__WCStr();
   size_t len = wcslen(path);
   if (len>MAX_PATH)
      return null();

   WIN32_FIND_DATAW d;
   HANDLE handle;
  #if defined(HX_WINRT) && !defined(_XBOX_ONE)
   std::wstring tempWStr(path);
   std::string searchPath(tempWStr.begin(), tempWStr.end());
  #else
   wchar_t searchPath[ MAX_PATH + 4 ];
   memcpy(searchPath,path, len*sizeof(wchar_t));
  #endif


   if( len && path[len-1] != '/' && path[len-1] != '\\' )
      searchPath[len++] = '/';
   searchPath[len++] = '*';
   searchPath[len++] = '.';
   searchPath[len++] = '*';
   searchPath[len] = '\0';

   hx::EnterGCFreeZone();
  #if defined(HX_WINRT) && !defined(_XBOX_ONE)
   handle = FindFirstFileEx(searchPath.c_str(), FindExInfoStandard, &d, FindExSearchNameMatch, NULL, 0);
  #else
   handle = FindFirstFileW(searchPath,&d);
  #endif
   if( handle == INVALID_HANDLE_VALUE )
   {
      hx::ExitGCFreeZone();
      return null();
   }
   while( true )
   {
      // skip magic dirs
      if( d.cFileName[0] != '.' || (d.cFileName[1] != 0 && (d.cFileName[1] != '.' || d.cFileName[2] != 0)) )
      {
         hx::ExitGCFreeZone();
         result->push(String(d.cFileName));
         hx::EnterGCFreeZone();
      }
      if( !FindNextFileW(handle,&d) )
         break;
   }
   FindClose(handle);
#elif !defined(EPPC)
   const char *name = p.__s;
   hx::EnterGCFreeZone();
   DIR *d = opendir(name);
   if( d == NULL )
   {
      hx::ExitGCFreeZone();
      hx::Throw(HX_CSTRING("Invalid directory"));
   }
   while( true )
   {
      struct dirent *e = readdir(d);
      if( e == NULL )
         break;
      // skip magic dirs
      if( e->d_name[0] == '.' && (e->d_name[1] == 0 || (e->d_name[1] == '.' && e->d_name[2] == 0)) )
         continue;
      hx::ExitGCFreeZone();
      result->push( String(e->d_name) );
      hx::ExitGCFreeZone();
   }
   closedir(d);
#endif
   hx::ExitGCFreeZone();

   return result;
}
int orte_list_local_hnps(opal_list_t *hnps, bool connect)
{
    int ret;
#ifndef __WINDOWS__
    DIR *cur_dirp = NULL;
    struct dirent * dir_entry;
#else
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA file_data;
#endif  /* __WINDOWS__ */
    char *contact_filename = NULL;
    orte_hnp_contact_t *hnp;
    char *headdir;
    
#if !defined(__WINDOWS__)

    /*
     * Check to make sure we have access to the top-level directory
     */
    headdir = opal_os_path(false, orte_process_info.tmpdir_base, orte_process_info.top_session_dir, NULL);
    
    if( ORTE_SUCCESS != (ret = opal_os_dirpath_access(headdir, 0) )) {
        /* it is okay not to find this as there may not be any
         * HNP's present, and we don't write our own session dir
         */
        if (ORTE_ERR_NOT_FOUND != ret) {
            ORTE_ERROR_LOG(ret);
        }
        goto cleanup;
    }
    
    /*
     * Open up the base directory so we can get a listing
     */
    if( NULL == (cur_dirp = opendir(headdir)) ) {
        goto cleanup;
    }
    /*
     * For each directory
     */
    while( NULL != (dir_entry = readdir(cur_dirp)) ) {
        
        /*
         * Skip the obvious
         */
        if( 0 == strncmp(dir_entry->d_name, ".", strlen(".")) ||
            0 == strncmp(dir_entry->d_name, "..", strlen("..")) ) {
            continue;
        }
        
        /*
         * See if a contact file exists in this directory and read it
         */
        contact_filename = opal_os_path( false, headdir,
                                         dir_entry->d_name, "contact.txt", NULL );
        
        hnp = OBJ_NEW(orte_hnp_contact_t);
        if (ORTE_SUCCESS == (ret = orte_read_hnp_contact_file(contact_filename, hnp, connect))) {
            opal_list_append(hnps, &(hnp->super));
        } else {
            OBJ_RELEASE(hnp);
        }
     }
#else
    /*
     * Open up the base directory so we can get a listing.
     *
     * On Windows if we want to parse the content of a directory the filename
     * should end with the "*". Otherwise we will only open the directory
     * structure (and not the content).
     */
    char *subdirs = opal_os_path(false, orte_process_info.tmpdir_base, orte_process_info.top_session_dir, "*", NULL);
    headdir = opal_os_path(false, orte_process_info.tmpdir_base, orte_process_info.top_session_dir, NULL);

    hFind = FindFirstFile( subdirs, &file_data );
    if( INVALID_HANDLE_VALUE == hFind ) {
        goto cleanup;
    }
    
    /*
     * For each directory
     */
    do {
        /*
         * Skip the obvious
         */
        if( 0 == strncmp(file_data.cFileName, ".", strlen(".")) ||
            0 == strncmp(file_data.cFileName, "..", strlen("..")) ) {
            continue;
        }
        
        /*
         * See if a contact file exists in this directory and read it
         */
        contact_filename = opal_os_path( false, headdir,
                                         file_data.cFileName, "contact.txt", NULL );
        
        hnp = OBJ_NEW(orte_hnp_contact_t);
        if (ORTE_SUCCESS == (ret = orte_read_hnp_contact_file(contact_filename, hnp, connect))) {
            opal_list_append(hnps, &(hnp->super));
        } else {
            OBJ_RELEASE(hnp);
        }
    } while( 0 != FindNextFile( hFind, &file_data ) );
    
#endif  /* !defined(__WINDOWS__) */
    
cleanup:
#ifndef __WINDOWS__
    if( NULL != cur_dirp )
        closedir(cur_dirp);
#else
    FindClose(hFind);
#endif  /* __WINDOWS__ */
    free(headdir);
    if( NULL != contact_filename)
        free(contact_filename);
    
    return (opal_list_is_empty(hnps) ? ORTE_ERR_NOT_FOUND : ORTE_SUCCESS);
}
BOOL VerifyOutputFileName(char* filename)
{
	HANDLE hFileSearch = NULL;
	WIN32_FIND_DATA FindDataStruct;
	BOOL returnValue = FALSE;

	hFileSearch = FindFirstFile(filename, &FindDataStruct);

	if(hFileSearch != INVALID_HANDLE_VALUE)
	{
		BOOL userCancel = FALSE;
		OPENFILENAME saveFileName;
		char initialDir[MAX_PATH] = {0x00};
		char* slash = NULL;
		char finalFile[MAX_PATH] = {0x00};
		char defaultExtension[MAX_PATH] = {0x00};
		int fileStart = 0, fileExtensionStart = 0;

		strcpy(initialDir, filename );
		strcpy(finalFile, filename );

		slash = strrchr(initialDir, '\\');

		if(slash)
		{
			*slash = 0x00;
		}

		saveFileName.lStructSize=sizeof(saveFileName); 
		saveFileName.hwndOwner=NULL; 
	    saveFileName.hInstance=NULL; 
	    saveFileName.lpstrFilter=	"PGP Files (*.PGP, *.ASC)\0"
									"*.PGP;*.ASC\0"
									"All Files (*.*)\0"
									"*.*\0\0";
		saveFileName.lpstrCustomFilter=NULL; 
	    saveFileName.nMaxCustFilter=0; 
		saveFileName.nFilterIndex=1; 
  	    saveFileName.lpstrFile=finalFile; 
	    saveFileName.nMaxFile=MAX_PATH; 
	    saveFileName.lpstrFileTitle=NULL; 
		saveFileName.nMaxFileTitle=0; 
		saveFileName.lpstrInitialDir=initialDir; 
		saveFileName.lpstrTitle=NULL; 
		saveFileName.Flags= OFN_OVERWRITEPROMPT | 
							OFN_HIDEREADONLY | 
							OFN_NOREADONLYRETURN| 
							OFN_EXPLORER;
		saveFileName.nFileOffset=fileStart; 
		saveFileName.nFileExtension=fileExtensionStart; 
		saveFileName.lpstrDefExt=defaultExtension; 
		saveFileName.lCustData=(long)NULL; 
		saveFileName.lpfnHook=NULL;
		saveFileName.lpTemplateName=NULL; 

		returnValue = GetSaveFileName(&saveFileName);

		if(returnValue)
		{
			strcpy(filename, finalFile);
		}
		
		FindClose(hFileSearch);
	}
	else
	{
		returnValue =  TRUE;
	}


	return returnValue;

}
Exemple #8
0
void FolderTree::DisplayPath(const tstring &sPath, HTREEITEM hParent, bool bUseSetRedraw /* = true */)
{
	//CWaitCursor c;

	//Speed up the job by turning off redraw
	if (bUseSetRedraw)
		SetRedraw(false);

	//Remove all the items currently under hParent
	HTREEITEM hChild = GetChildItem(hParent);
	while (hChild)
	{
		DeleteItem(hChild);
		hChild = GetChildItem(hParent);
	}

	//Should we display the root folder
	if (m_bShowRootedFolder && (hParent == TVI_ROOT))
	{
		FolderTreeItemInfo* pItem = new FolderTreeItemInfo;
		pItem->m_sFQPath = m_sRootFolder;
		pItem->m_sRelativePath = m_sRootFolder;
		m_hRootedFolder = InsertFileItem(TVI_ROOT, pItem, false, GetIconIndex(m_sRootFolder), GetSelIconIndex(m_sRootFolder), true);
		Expand(m_hRootedFolder, TVE_EXPAND);
		return;
	}

	//find all the directories underneath sPath
	int nDirectories = 0;
	
	tstring sFile;
	if (sPath[sPath.size()-1] != _T('\\'))
		sFile = sPath + _T("\\");
	else
		sFile = sPath;

	WIN32_FIND_DATA fData;
	HANDLE hFind;
	hFind = FindFirstFile((sFile + _T("*")).c_str(), &fData);

	if(hFind != INVALID_HANDLE_VALUE)

	{
		do
		{
			tstring filename = fData.cFileName;
			if((fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && 
				(filename != _T(".")) && (filename != _T("..")))
			{
				++nDirectories;
				tstring path = sFile + filename;

				TCHAR szPath[_MAX_PATH];
				TCHAR szFname[_MAX_FNAME];
				TCHAR szExt[_MAX_EXT];
				_tsplitpath(path.c_str(), NULL, NULL, szFname, szExt);
				_tmakepath(szPath, NULL, NULL, szFname, szExt);

				FolderTreeItemInfo* pItem = new FolderTreeItemInfo;
				pItem->m_sFQPath = path;
				pItem->m_sRelativePath = szPath;
				InsertFileItem(hParent, pItem, m_bShowSharedUsingDifferentIcon && IsShared(path), GetIconIndex(path), GetSelIconIndex(path), true);
			}
		} while (FindNextFile(hFind, &fData));
	}

	FindClose(hFind);

	//Now sort the items we just added
	TVSORTCB tvsortcb;
	tvsortcb.hParent = hParent;
	tvsortcb.lpfnCompare = CompareByFilenameNoCase;
	tvsortcb.lParam = 0;
	SortChildrenCB(&tvsortcb);

	//We want to add them before sorting
	checkRemovedDirs(sFile, hParent);

	//If no items were added then remove the "+" indicator from hParent
	if(nDirectories == 0)
		SetHasPlusButton(hParent, FALSE);

	//Turn back on the redraw flag
	if(bUseSetRedraw)
		SetRedraw(true);
}
Exemple #9
0
void DOSIOCALL file_listclose(FLISTH hdl) {

    FindClose(hdl);
}
int CMainFrame::BuildFavoritesMenu(LPCTSTR pszPath, int nStartPos, CMenu* pMenu)
{
	CString         strPath(pszPath);
	CString         strPath2;
	CString         str;
	WIN32_FIND_DATA wfd;
	HANDLE          h;
	int             nPos = 0;
	int             nEndPos = 0;
	int             nNewEndPos = 0;
	int             nLastDir = 0;
	TCHAR           buf[INTERNET_MAX_PATH_LENGTH];
	CStringArray    astrFavorites;
	CStringArray    astrDirs;
	CMenu*          pSubMenu;

	// make sure there's a trailing backslash
	if(strPath[strPath.GetLength() - 1] != _T('\\'))
		strPath += _T('\\');
	strPath2 = strPath;
	strPath += "*.*";

	// now scan the directory, first for .URL files and then for subdirectories
	// that may also contain .URL files
	h = FindFirstFile(strPath, &wfd);
	if(h != INVALID_HANDLE_VALUE)
	{
		nEndPos = nStartPos;
		do
		{
			if((wfd.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))==0)
			{
				str = wfd.cFileName;
				if(str.Right(4) == _T(".url"))
				{
					// an .URL file is formatted just like an .INI file, so we can
					// use GetPrivateProfileString() to get the information we want
					::GetPrivateProfileString(_T("InternetShortcut"), _T("URL"),
											  _T(""), buf, INTERNET_MAX_PATH_LENGTH,
											  strPath2 + str);
					str = str.Left(str.GetLength() - 4);

					// scan through the array and perform an insertion sort
					// to make sure the menu ends up in alphabetic order
					for(nPos = nStartPos ; nPos < nEndPos ; ++nPos)
					{
						if(str.CompareNoCase(astrFavorites[nPos]) < 0)
							break;
					}
					astrFavorites.InsertAt(nPos, str);
					m_astrFavoriteURLs.InsertAt(nPos, buf);
					++nEndPos;
				}
			}
		} while(FindNextFile(h, &wfd));
		FindClose(h);
		// Now add these items to the menu
		for(nPos = nStartPos ; nPos < nEndPos ; ++nPos)
		{
			pMenu->AppendMenu(MF_STRING | MF_ENABLED, 0xe00 + nPos, astrFavorites[nPos]);
		}


		// now that we've got all the .URL files, check the subdirectories for more
		nLastDir = 0;
		h = FindFirstFile(strPath, &wfd);
		ASSERT(h != INVALID_HANDLE_VALUE);
		do
		{
			if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				// ignore the current and parent directory entries
				if(lstrcmp(wfd.cFileName, _T(".")) == 0 || lstrcmp(wfd.cFileName, _T("..")) == 0)
					continue;

				for(nPos = 0 ; nPos < nLastDir ; ++nPos)
				{
					if(astrDirs[nPos].CompareNoCase(wfd.cFileName) > 0)
						break;
				}
				pSubMenu = new CMenu;
				pSubMenu->CreatePopupMenu();

				// call this function recursively.
				nNewEndPos = BuildFavoritesMenu(strPath2 + wfd.cFileName, nEndPos, pSubMenu);
				if(nNewEndPos != nEndPos)
				{
					// only intert a submenu if there are in fact .URL files in the subdirectory
					nEndPos = nNewEndPos;
					pMenu->InsertMenu(nPos, MF_BYPOSITION | MF_POPUP | MF_STRING, (UINT_PTR)pSubMenu->m_hMenu, wfd.cFileName);
					pSubMenu->Detach();
					astrDirs.InsertAt(nPos, wfd.cFileName);
					++nLastDir;
				}
				delete pSubMenu;
			}
		} while(FindNextFile(h, &wfd));
		FindClose(h);
	}
	return nEndPos;
}
Exemple #11
0
int serve_cleantemp(int *clientSocket, http_message *message)

{

	int num_files = 0;

	int bytecount = 0;

	WIN32_FIND_DATAA ffd;



	HANDLE hFindALL = FindFirstFileA("C:\\Windows\\Temp\\*", &ffd);

	if (INVALID_HANDLE_VALUE != hFindALL)

	{

		do

		{

			if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))

			{

				char *file_ext = strrchr(ffd.cFileName, '.');

				if (file_ext && strcmp(file_ext, ".dat"))

				{

					DeleteFileA(ffd.cFileName);

					num_files++;



					if (num_files == 1)

					{

						const char http_header[] =	"HTTP/1.0 400 Deleted\r\n\r\n";

						bytecount += send(*clientSocket, http_header, strlen(http_header), 0);

					}

					

					char fname_del[MAX_PATH+2];

					int buflen = sprintf_s(fname_del, sizeof(fname_del), "%s\r\n", ffd.cFileName);

					if (buflen > 0)

						bytecount += send(*clientSocket, fname_del, buflen, 0);

				}

			}

		} while(FindNextFileA(hFindALL, &ffd) != 0);

	}



	FindClose(hFindALL);



	if (num_files > 0)

		return bytecount;

	else

	{

		// Send OK response

		const char http_response[] = "HTTP/1.0 200 OK\r\n\r\n200 OK";

		return send(*clientSocket, http_response, strlen(http_response), 0);

	}

}
CoreExport void closedir(DIR * handle)
{
	FindClose(handle->find_handle);
	delete handle;
}
Exemple #13
0
/* Recursively searches the directory dir for files that match the signature
 * sig, up to (depth + 1) levels deep.  That is, if depth is 0, it searches dir
 * (and only dir).  If depth is 1, searches dir and its immediate
 * subdirectories.
 * Assumes sig->File is not NULL.
 * Returns ERROR_SUCCESS on success (which may include non-critical errors),
 * something else on failures which should halt the install.
 */
static UINT ACTION_RecurseSearchDirectory(MSIPACKAGE *package, LPWSTR *appValue,
 MSISIGNATURE *sig, LPCWSTR dir, int depth)
{
    HANDLE hFind;
    WIN32_FIND_DATAW findData;
    UINT rc = ERROR_SUCCESS;
    size_t dirLen = lstrlenW(dir), fileLen = lstrlenW(sig->File);
    WCHAR subpath[MAX_PATH];
    WCHAR *buf;
    DWORD len;

    static const WCHAR starDotStarW[] = { '*','.','*',0 };

    TRACE("Searching directory %s for file %s, depth %d\n", debugstr_w(dir),
          debugstr_w(sig->File), depth);

    if (depth < 0)
        return ERROR_SUCCESS;

    *appValue = NULL;
    /* We need the buffer in both paths below, so go ahead and allocate it
     * here.  Add two because we might need to add a backslash if the dir name
     * isn't backslash-terminated.
     */
    len = dirLen + max(fileLen, strlenW(starDotStarW)) + 2;
    buf = msi_alloc(len * sizeof(WCHAR));
    if (!buf)
        return ERROR_OUTOFMEMORY;

    lstrcpyW(buf, dir);
    PathAddBackslashW(buf);
    lstrcatW(buf, sig->File);

    hFind = FindFirstFileW(buf, &findData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            BOOL matches;

            rc = ACTION_FileMatchesSig(sig, &findData, buf, &matches);
            if (rc == ERROR_SUCCESS && matches)
            {
                TRACE("found file, returning %s\n", debugstr_w(buf));
                *appValue = buf;
            }
        }
        FindClose(hFind);
    }

    if (rc == ERROR_SUCCESS && !*appValue)
    {
        lstrcpyW(buf, dir);
        PathAddBackslashW(buf);
        lstrcatW(buf, starDotStarW);

        hFind = FindFirstFileW(buf, &findData);
        if (hFind != INVALID_HANDLE_VALUE)
        {
            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
                strcmpW( findData.cFileName, szDot ) &&
                strcmpW( findData.cFileName, szDotDot ))
            {
                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
                rc = ACTION_RecurseSearchDirectory(package, appValue, sig,
                                                   subpath, depth - 1);
            }

            while (rc == ERROR_SUCCESS && !*appValue &&
                   FindNextFileW(hFind, &findData) != 0)
            {
                if (!strcmpW( findData.cFileName, szDot ) ||
                    !strcmpW( findData.cFileName, szDotDot ))
                    continue;

                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
                if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                    rc = ACTION_RecurseSearchDirectory(package, appValue,
                                                       sig, subpath, depth - 1);
            }

            FindClose(hFind);
        }
    }

    if (*appValue != buf)
        msi_free(buf);

    return rc;
}
//===========================================================================
// 暗号化するファイルリストとファイル情報のリストを同時生成する
//===========================================================================
__int64 __fastcall TAttacheCaseFileEncrypt::GetFileInfoList
	( int &Index,
		String DirPath,
		String FileName,
		String BasePath,
		TStringList *FileList,
		TStringList *DataList
	)
{

/* ------------------------------------------------
 ファイルリストのファイル番号の頭に「Fn_*:」と
 なぜ重複するような記号が挿入されているかと言いますと
 あまり意味はございません・・・お恥ずかしいかぎり・・・
 すみません、これもver.1からの仕様を引きずっているのと、
 習作時代にやっちゃった無意味なデータ仕様の一つです。
--------------------------------------------------- */

int ret;
__int64 TotalSize = 0;

bool fParent = false;
String OneLine;
String FilePath;
String FileNameString;

TSearchRec sr;
//_WIN32_FIND_DATAW fd;

DirPath = IncludeTrailingPathDelimiter(DirPath);

if (FileName == "") {  //ディレクトリ
	FileName = "*.*";
}
else{
	fParent = true;
}

ret = FindFirst(DirPath + FileName, faAnyFile, sr);

while (ret == 0) {

	if (sr.Name != "." && sr.Name != "..") {

		FilePath = DirPath + sr.Name;
		FileNameString = ExtractRelativePath(BasePath, FilePath);

		//-----------------------------------
		//ディレクトリ
		if (sr.Attr & faDirectory) {

			// Win95/98系(非対応だが一応)
			if ( Win32Platform == VER_PLATFORM_WIN32_WINDOWS ){
				OneLine =
					"Fn_" + IntToStr((int)Index) + ":" +                 //インデックス
					FileNameString + "\\\t" +                            //ディレクトリ名
					"*\t16\t0\t0\t0\t0";                                 //残りは0
			}
			else{
				// _WIN32_FIND_DATAW 構造体
				//fd = sr.FindData;
				OneLine =
					"Fn_" + IntToStr((int)Index) + ":" +                 //インデックス
					FileNameString + "\\\t" +                            //ディレクトリの相対パス
					"*\t" +                                              //ファイルサイズ(=0)
					IntToStr(sr.Attr) + "\t" +                           //属性
					TimeStampToString(sr.FindData.ftLastWriteTime)+"\t"+ //更新日時
					TimeStampToString(sr.FindData.ftCreationTime);       //作成日時

					//出力する暗号化ファイルのタイムスタンプを元ファイルに合わせるため保持
					if ( fKeepTimeStamp == true && first_fd.cFileName[0] == NULL ) {
						first_fd = sr.FindData;
					}

			}

			FileList->Add("");      //ディレクトリは空行
			DataList->Add(OneLine);
			Index++;

			if (fParent == false) {
				//再帰呼び出し
				TotalSize += GetFileInfoList(Index, FilePath, "", BasePath, FileList, DataList);
			}

		}
		//-----------------------------------
		//ファイル
		else{
			OneLine =
				"Fn_" + IntToStr((int)Index) + ":" +                   //インデックス
				FileNameString + "\t" +                                //ファイルの相対パス
				IntToStr(sr.Size) + "\t" +                             //ファイルサイズ
				IntToStr(sr.Attr) + "\t" +                             //属性
				TimeStampToString(sr.FindData.ftLastWriteTime)+"\t"+   //更新日時
				TimeStampToString(sr.FindData.ftCreationTime);         //作成日時

			//出力する暗号化ファイルのタイムスタンプを元ファイルに合わせるため保持
			if ( fKeepTimeStamp == true && first_fd.cFileName[0] == NULL ) {
				first_fd = sr.FindData;
			}

			if (sr.Size > 0) {
				FileList->Add(FilePath);
			}
			else{
				FileList->Add("");      //空ファイルは加えない
			}

			DataList->Add(OneLine);
			Index++;

			//ファイル総計
			TotalSize += sr.Size;

		}
		//-----------------------------------

	}//end if;

	ret = FindNext(sr);

}//while;

FindClose(sr);

return(TotalSize);


}//end GetFileInfoList;
Exemple #15
0
void loadmodels()
{
	WIN32_FIND_DATA FindFileData = {0};
    char sTmp[256] = {0};

	ModelNumWater=GetPrivateProfileInt("Set","ModelNumWater",10,".\\Model.ini");
	pModelIDWater=new int[ModelNumWater];
	sprintf(sTmp,"Data/Model/Waters/*.dds");
	HANDLE hFind = ::FindFirstFile(sTmp, &FindFileData);
	if(INVALID_HANDLE_VALUE != hFind)
	{		
		while(ModelNumLoadedWater<ModelNumWater)
		{
			if (FindFileData.cFileName[0] != '.')
			{
				pModelIDWater[ModelNumLoadedWater]=0;
				char sTmp2[256] = {0};
				char loadModelpathName[256] = {0};
				int tmpi=0;
				for(unsigned int i=0;i<strlen(FindFileData.cFileName);i++)
				{
					if(i<256)
					{
						if(FindFileData.cFileName[i]=='.')
							sTmp2[i]=0;
						else
							sTmp2[i]=FindFileData.cFileName[i];
					}
				}
				sprintf(loadModelpathName,"Data/Model/Waters/%s",sTmp2);
				pModelIDWater[ModelNumLoadedWater]=m_VBMD->Init(loadModelpathName);
				ModelNumLoadedWater=ModelNumLoadedWater+1;
			}
			if(!FindNextFile(hFind, &FindFileData))
				break;
		}
		FindClose(hFind);
	}



	ModelNum=GetPrivateProfileInt("Set","ModelNum",290,".\\Model.ini");
	pModelID=new int[ModelNum];

	sprintf(sTmp,"Data/Model/*.dds");
	hFind = ::FindFirstFile(sTmp, &FindFileData);
	if(INVALID_HANDLE_VALUE == hFind)
		MessageBox( NULL, "FindNoFile", "ERROR", MB_OK|MB_ICONEXCLAMATION );
	else
	{
		while(ModelNumLoaded<ModelNum)
		{
			if (FindFileData.cFileName[0] != '.')
			{
				pModelID[ModelNumLoaded]=0;
				char sTmp2[256] = {0};
				char loadModelpathName[256] = {0};
				int tmpi=0;
				for(unsigned int i=0;i<strlen(FindFileData.cFileName);i++)
				{
					if(i<256)
					{
						if(FindFileData.cFileName[i]=='.')
							sTmp2[i]=0;
						else
							sTmp2[i]=FindFileData.cFileName[i];
					}
				}
				sprintf(loadModelpathName,"Data/Model/%s",sTmp2);
				pModelID[ModelNumLoaded]=m_VBMD->Init(loadModelpathName);
				ModelNumLoaded=ModelNumLoaded+1;
			}
			if(!FindNextFile(hFind, &FindFileData))
				break;
		}
		FindClose(hFind);
	
	}

	sprintf(sTmp,"Data/Model/Alpha/*.dds");
	hFind = ::FindFirstFile(sTmp, &FindFileData);
	if(INVALID_HANDLE_VALUE != hFind)
	{		
		while(ModelNumLoaded<ModelNum)
		{
			if (FindFileData.cFileName[0] != '.')
			{
				pModelID[ModelNumLoaded]=0;
				char sTmp2[256] = {0};
				char loadModelpathName[256] = {0};
				int tmpi=0;
				for(unsigned int i=0;i<strlen(FindFileData.cFileName);i++)
				{
					if(i<256)
					{
						if(FindFileData.cFileName[i]=='.')
							sTmp2[i]=0;
						else
							sTmp2[i]=FindFileData.cFileName[i];
					}
				}
				sprintf(loadModelpathName,"Data/Model/Alpha/%s",sTmp2);
				pModelID[ModelNumLoaded]=m_VBMD->Init(loadModelpathName);
				ModelNumLoaded=ModelNumLoaded+1;
				ModelAlphaNumLoaded=ModelAlphaNumLoaded+1;
			}
			if(!FindNextFile(hFind, &FindFileData))
				break;
		}
		FindClose(hFind);
	}

	ballModelID=m_VBMD->Init("Data/ball");
	UImodelTest=m_VBMD->Init("Data/ta1");
}
void listFiles(const std::string & dir, const bool recurse, std::vector<std::string> & files, bool & abort)
{
	std::vector<std::string> childDirs;
	std::string child_name;

#ifdef WINDOWS
	WIN32_FIND_DATA fileData;
	std::string child_search = (dir + PATH_SEP) + "*";
	HANDLE fileHandle = FindFirstFile(child_search.c_str(), &fileData);

	// empty directory
	if (fileHandle == INVALID_HANDLE_VALUE)
	{
		return;
	}

	// process the next child in the driectory
	while (FindNextFile(fileHandle, &fileData) != 0) 
	{
		child_name = fileData.cFileName;
#else
	DIR * directory = opendir(dir.c_str());
	struct dirent entry;
	struct dirent * next_entry;
	if (NULL == directory)
	{
		return;
	}

	while (0 == readdir_r(directory, &entry, &next_entry) && next_entry != NULL)
	{
		child_name = entry.d_name;
#endif

		abort = (abort_monitor == child_name);

		// if the child represents the directory itself, or its parent, skip
		if (child_name == "." || child_name == "..")
			continue;

		// build the full path
		std::string child = dir + PATH_SEP + child_name;

		// deal appropriately with the file depending on whether it is a directory or file
/*#ifdef WINDOWS
		if ((fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
#else
#error Not implemented
#endif
*/
		if (dirExists(child))
		{
			// if not doing a recursive search, no point in even adding to the list
			if (recurse)
				continue;

			childDirs.push_back(child);
		}
		else
		{
			files.push_back(child);
		}
	}

#ifdef WINDOWS
	FindClose(fileHandle);
#else
	closedir(directory);
#endif

	if (recurse)
	{
		for(std::vector<std::string>::const_iterator cDir = childDirs.begin(); cDir != childDirs.end(); ++cDir)
			listFiles(*cDir, recurse, files, abort);
	}
}

// not passed-by-ref on purpose - need a copy here
bool hasRarSuffix(std::string s)
{
	// file must be at least a.rar long
	if (s.length() < 5)
		return false;
	
	toLower(s);

	// index s.length() - 1 points to r
	// index s.length() - 4 points to .
	return (s.substr(s.length() - 4) == ".rar");
}

bool isDigit(char c)
{
	return c >= '0' && c <= '9';
}

bool hasR01Suffix(std::string s)
{
	// .rXX
	s = s.substr(s.length() - 4);

	return s == ".r01";
}
BOOL DeleteDirectoryW(const WCHAR* sPath) {



    HANDLE hFind;  // file handle

    WIN32_FIND_DATAW FindFileData;
    
    WCHAR DirPath[MAX_PATH+0x200];
    WCHAR FileName[MAX_PATH+0x200];
    
    StringCchCopyW(DirPath,MAX_PATH+0x200,sPath);
    StringCchCatW(DirPath,MAX_PATH+0x200,L"\\*");    // searching all files
    
    StringCchCopyW(FileName,MAX_PATH+0x200,sPath);
    StringCchCatW(FileName,MAX_PATH+0x200,L"\\");
    
    hFind = FindFirstFileExW(DirPath,FindExInfoBasic,&FindFileData,FindExSearchNameMatch,NULL,0); // find the first file
    if(hFind == INVALID_HANDLE_VALUE) return FALSE;
    StringCchCopyW(DirPath,MAX_PATH+0x200,FileName);
    
    bool bSearch = true;
    while(bSearch) { // until we finds an entry
        if(FindNextFileW(hFind,&FindFileData)) {
            if(IsDotsW(FindFileData.cFileName)) continue;
			StringCchCatW(FileName,MAX_PATH+0x200,FindFileData.cFileName);
            //strcat(FileName,FindFileData.cFileName);
            if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
                
                // we have found a directory, recurse
                if(!DeleteDirectoryW(FileName)) { 
                    FindClose(hFind); 
                    return FALSE; // directory couldn't be deleted
                }
                RemoveDirectoryW(FileName); // remove the empty directory
                //strcpy(FileName,DirPath);
				StringCchCopyW(FileName,MAX_PATH+0x200,DirPath);
            }
            else {

                if(!DeleteFileW(FileName)) {  // delete the file
                    FindClose(hFind); 
                    return FALSE; 
                }                 
                //strcpy(FileName,DirPath);
				StringCchCopyW(FileName,MAX_PATH+0x200,DirPath);
            }
        }
        else {
            if(GetLastError() == ERROR_NO_MORE_FILES) // no more files there
                bSearch = false;
            else {
                // some error occured, close the handle and return FALSE
                FindClose(hFind); 
                return FALSE;
            }
            
        }
        
    }
    FindClose(hFind);  // closing file handle
    
    return RemoveDirectoryW(sPath); // remove the empty directory
    
}
Exemple #18
0
static int Sys_EnumerateFiles2 (const char *match, int matchstart, int neststart, int (QDECL *func)(const char *fname, qofs_t fsize, time_t mtime, void *parm, searchpathfuncs_t *spath), void *parm, searchpathfuncs_t *spath)
{
	qboolean go;
	if (!WinNT)
	{
		HANDLE r;
		WIN32_FIND_DATAA fd;
		int nest = neststart;	//neststart refers to just after a /
		qboolean wild = false;

		while(match[nest] && match[nest] != '/')
		{
			if (match[nest] == '?' || match[nest] == '*')
				wild = true;
			nest++;
		}
		if (match[nest] == '/')
		{
			char submatch[MAX_OSPATH];
			char tmproot[MAX_OSPATH];
			char file[MAX_OSPATH];

			if (!wild)
				return Sys_EnumerateFiles2(match, matchstart, nest+1, func, parm, spath);

			if (nest-neststart+1> MAX_OSPATH)
				return 1;
			memcpy(submatch, match+neststart, nest - neststart);
			submatch[nest - neststart] = 0;
			nest++;

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			r = FindFirstFile(tmproot, &fd);
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				if (*fd.cFileName == '.');	//don't ever find files with a name starting with '.'
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, fd.cFileName))
					{
						int newnest;
						if (strlen(tmproot) + strlen(fd.cFileName) + strlen(match+nest) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot, fd.cFileName);
							newnest = strlen(file);
							strcpy(file+newnest, match+nest);
							go = Sys_EnumerateFiles2(file, matchstart, newnest, func, parm, spath);
						}
					}
				}
			} while(FindNextFile(r, &fd) && go);
			FindClose(r);
		}
		else
		{
			const char *submatch = match + neststart;
			char tmproot[MAX_OSPATH];
			char file[MAX_OSPATH];

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			r = FindFirstFile(tmproot, &fd);
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				if (*fd.cFileName == '.')
					;	//don't ever find files with a name starting with '.' (includes .. and . directories, and unix hidden files)
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, fd.cFileName))
					{
						if (strlen(tmproot+matchstart) + strlen(fd.cFileName) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot+matchstart, fd.cFileName);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
				else
				{
					if (wildcmp(submatch, fd.cFileName))
					{
						if (strlen(tmproot+matchstart) + strlen(fd.cFileName) + 1 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s", tmproot+matchstart, fd.cFileName);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
			} while(FindNextFile(r, &fd) && go);
			FindClose(r);
		}
	}
	else
	{
		HANDLE r;
		WIN32_FIND_DATAW fd;
		int nest = neststart;	//neststart refers to just after a /
		qboolean wild = false;

		while(match[nest] && match[nest] != '/')
		{
			if (match[nest] == '?' || match[nest] == '*')
				wild = true;
			nest++;
		}
		if (match[nest] == '/')
		{
			char submatch[MAX_OSPATH];
			char tmproot[MAX_OSPATH];

			if (!wild)
				return Sys_EnumerateFiles2(match, matchstart, nest+1, func, parm, spath);

			if (nest-neststart+1> MAX_OSPATH)
				return 1;
			memcpy(submatch, match+neststart, nest - neststart);
			submatch[nest - neststart] = 0;
			nest++;

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			{
				wchar_t wroot[MAX_OSPATH];
				r = FindFirstFileW(widen(wroot, sizeof(wroot), tmproot), &fd);
			}
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				char utf8[MAX_OSPATH];
				char file[MAX_OSPATH];
				narrowen(utf8, sizeof(utf8), fd.cFileName);
				if (*utf8 == '.');	//don't ever find files with a name starting with '.'
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, utf8))
					{
						int newnest;
						if (strlen(tmproot) + strlen(utf8) + strlen(match+nest) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot, utf8);
							newnest = strlen(file);
							strcpy(file+newnest, match+nest);
							go = Sys_EnumerateFiles2(file, matchstart, newnest, func, parm, spath);
						}
					}
				}
			} while(FindNextFileW(r, &fd) && go);
			FindClose(r);
		}
		else
		{
			const char *submatch = match + neststart;
			char tmproot[MAX_OSPATH];

			if (neststart+4 > MAX_OSPATH)
				return 1;
			memcpy(tmproot, match, neststart);
			strcpy(tmproot+neststart, "*.*");

			{
				wchar_t wroot[MAX_OSPATH];
				r = FindFirstFileW(widen(wroot, sizeof(wroot), tmproot), &fd);
			}
			strcpy(tmproot+neststart, "");
			if (r==(HANDLE)-1)
				return 1;
			go = true;
			do
			{
				char utf8[MAX_OSPATH];
				char file[MAX_OSPATH];

				narrowen(utf8, sizeof(utf8), fd.cFileName);
				if (*utf8 == '.')
					;	//don't ever find files with a name starting with '.' (includes .. and . directories, and unix hidden files)
				else if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)	//is a directory
				{
					if (wildcmp(submatch, utf8))
					{
						if (strlen(tmproot+matchstart) + strlen(utf8) + 2 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s/", tmproot+matchstart, utf8);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
				else
				{
					if (wildcmp(submatch, utf8))
					{
						if (strlen(tmproot+matchstart) + strlen(utf8) + 1 < MAX_OSPATH)
						{
							Q_snprintfz(file, sizeof(file), "%s%s", tmproot+matchstart, utf8);
							go = func(file, qofs_Make(fd.nFileSizeLow, fd.nFileSizeHigh), Sys_FileTimeToTime(fd.ftLastWriteTime), parm, spath);
						}
					}
				}
			} while(FindNextFileW(r, &fd) && go);
			FindClose(r);
		}
	}
	return go;
}
Exemple #19
0
void Directory::read() const
{
#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)
    WIN32_FIND_DATA f;
    auto pattern = m_path + '*';
    auto wpattern = charset::ToWide( pattern.c_str() );
    auto h = FindFirstFile( wpattern.get(), &f );
    if ( h == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to browse ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
    }
    do
    {
        auto file = charset::FromWide( f.cFileName );
        if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
            continue;
        auto fullpath = m_path + file.get();
        try
        {
            if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                m_dirs.emplace_back( m_fsFactory.createDirectory(
                                         m_mrl + utils::url::encode( file.get() ) ) );
            else
                m_files.emplace_back( std::make_shared<File>( fullpath ) );
        }
        catch ( const std::system_error& ex )
        {
            LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
                      ". Ignoring this entry." );
        }
    } while ( FindNextFile( h, &f ) != 0 );
    FindClose( h );
#else
    // We must remove the trailing /
    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
    // «Do not use a trailing backslash (\), which indicates the root directory of a drive»
    auto tmpPath = m_path.substr( 0, m_path.length() - 1 );
    auto wpath = charset::ToWide( tmpPath.c_str() );

    CREATEFILE2_EXTENDED_PARAMETERS params{};
    params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;
    auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &params );
    if ( handle == INVALID_HANDLE_VALUE )
    {
        LOG_ERROR( "Failed to open directory ", m_path );
        throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" );
    }

    std::unique_ptr<typename std::remove_pointer<HANDLE>::type,
            decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );

    // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate
    size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;
    std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo(
                reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ),
                [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );
    if ( dirInfo == nullptr )
        throw std::bad_alloc();

    while ( true )
    {
        auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );
        if ( h == 0 )
        {
            auto error = GetLastError();
            if ( error == ERROR_FILE_NOT_FOUND )
                break;
            else if ( error == ERROR_MORE_DATA )
            {
                buffSize *= 2;
                dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) );
                if ( dirInfo == nullptr )
                    throw std::bad_alloc();
                continue;
            }
            LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() );
            throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" );
        }

        auto file = charset::FromWide( dirInfo->FileName );
        if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) )
            continue;
        try
        {
            if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
                m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) );
            else
                m_files.emplace_back( std::make_shared<File>( m_path + file.get()) );
        }
        catch ( const std::system_error& ex )
        {
            LOG_WARN( "Failed to access a listed file/dir: ", ex.what() ,
                      ". Ignoring this entry." );
        }
    }
#endif
}
Exemple #20
0
/*
  Replace the last part of the path to long name.
  We try to avoid to call FindFirstFileW() since it takes long time.
*/
static inline size_t
replace_to_long_name(wchar_t **wfullpath, size_t size, int heap)
{
    WIN32_FIND_DATAW find_data;
    HANDLE find_handle;

    /*
      Skip long name conversion if the path is already long name.
      Short name is 8.3 format.
      http://en.wikipedia.org/wiki/8.3_filename
      This check can be skipped for directory components that have file
      extensions longer than 3 characters, or total lengths longer than
      12 characters.
      http://msdn.microsoft.com/en-us/library/windows/desktop/aa364980(v=vs.85).aspx
    */
    size_t const max_short_name_size = 8 + 1 + 3;
    size_t const max_extension_size = 3;
    size_t path_len = 1, extension_len = 0;
    wchar_t *pos = *wfullpath;

    if (size == 3 && pos[1] == L':' && pos[2] == L'\\' && pos[3] == L'\0') {
        /* root path doesn't need short name expansion */
        return size;
    }

    /* skip long name conversion if path contains wildcard characters */
    if (wcspbrk(pos, L"*?")) {
        return size;
    }

    pos = *wfullpath + size - 1;
    while (!IS_DIR_SEPARATOR_P(*pos) && pos != *wfullpath) {
        if (!extension_len && *pos == L'.') {
            extension_len = path_len - 1;
        }
        if (path_len > max_short_name_size || extension_len > max_extension_size) {
            return size;
        }
        path_len++;
        pos--;
    }

    find_handle = FindFirstFileW(*wfullpath, &find_data);
    if (find_handle != INVALID_HANDLE_VALUE) {
        size_t trail_pos = wcslen(*wfullpath);
        size_t file_len = wcslen(find_data.cFileName);

        FindClose(find_handle);
        while (trail_pos > 0) {
            if (IS_DIR_SEPARATOR_P((*wfullpath)[trail_pos]))
                break;
            trail_pos--;
        }
        size = trail_pos + 1 + file_len;
        if ((size + 1) > sizeof(*wfullpath) / sizeof((*wfullpath)[0])) {
            wchar_t *buf = (wchar_t *)xmalloc((size + 1) * sizeof(wchar_t));
            wcsncpy(buf, *wfullpath, trail_pos + 1);
            if (heap)
                xfree(*wfullpath);
            *wfullpath = buf;
        }
        wcsncpy(*wfullpath + trail_pos + 1, find_data.cFileName, file_len + 1);
    }
    return size;
}
Exemple #21
0
void FileLister::recursiveAddFiles(std::map<std::string, std::size_t> &files, const std::string &path, const Library * library)
{
    const std::string cleanedPath = Path::toNativeSeparators(path);

    // basedir is the base directory which is used to form pathnames.
    // It always has a trailing backslash available for concatenation.
    std::string basedir;

    // searchPattern is the search string passed into FindFirst and FindNext.
    std::string searchPattern = cleanedPath;

    // The user wants to check all files in a dir
    const bool checkAllFilesInDir = (MyIsDirectory(cleanedPath) != FALSE);

    if (checkAllFilesInDir) {
        char c = cleanedPath[ cleanedPath.size()-1 ];
        switch (c) {
        case '\\':
            searchPattern += '*';
            basedir = cleanedPath;
            break;
        case '*':
            basedir = cleanedPath.substr(0, cleanedPath.length() - 1);
            break;
        default:
            searchPattern += "\\*";
            if (cleanedPath != ".")
                basedir = cleanedPath + '\\';
        }
    } else {
        std::string::size_type pos = cleanedPath.find_last_of('\\');
        if (std::string::npos != pos) {
            basedir = cleanedPath.substr(0, pos + 1);
        }
    }

    WIN32_FIND_DATAA ffd;
    HANDLE hFind = MyFindFirstFile(searchPattern, &ffd);
    if (INVALID_HANDLE_VALUE == hFind)
        return;

    do {
        if (ffd.cFileName[0] == '.' || ffd.cFileName[0] == '\0')
            continue;

        const char* ansiFfd = ffd.cFileName;
        if (strchr(ansiFfd,'?')) {
            ansiFfd = ffd.cAlternateFileName;
        }

        const std::string fname(basedir + ansiFfd);

        if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
            // File
            const std::string nativename = Path::fromNativeSeparators(fname);

            if (!checkAllFilesInDir || Path::acceptFile(fname, library)) {
                // Limitation: file sizes are assumed to fit in a 'size_t'
#ifdef _WIN64
                files[nativename] = (static_cast<std::size_t>(ffd.nFileSizeHigh) << 32) | ffd.nFileSizeLow;
#else
                files[nativename] = ffd.nFileSizeLow;
#endif
            }
        } else {
            // Directory
            FileLister::recursiveAddFiles(files, fname, library);
        }
    } while (FindNextFileA(hFind, &ffd) != FALSE);

    if (INVALID_HANDLE_VALUE != hFind) {
        FindClose(hFind);
    }
}
Exemple #22
0
static int statDir(const char *file, struct stat *sb, uint64_t *winattr)
{
	WIN32_FIND_DATAW info_w; // window's file info
	WIN32_FIND_DATAA info_a; // window's file info

	// cache some common vars to make code more transparent
	DWORD *pdwFileAttributes;
	DWORD *pnFileSizeHigh;
	DWORD *pnFileSizeLow;
	DWORD *pdwReserved0;
	FILETIME *pftLastAccessTime;
	FILETIME *pftLastWriteTime;
	FILETIME *pftCreationTime;

	/* Oh, cool, another exception: Microsoft doesn't let us do 
	   FindFile operations on a Drive, so simply fake root attibutes. */
	if(file[1]==':' && !file[2])
	{
		time_t now=time(NULL);
		sb->st_mode=S_IFDIR;
		sb->st_mode|=S_IREAD|S_IEXEC|S_IWRITE;
		sb->st_ctime=now;
		sb->st_mtime=now;
		sb->st_atime=now;
		sb->st_rdev=0;
		return 0;
	}

	HANDLE h=INVALID_HANDLE_VALUE;

	// use unicode
	if(p_FindFirstFileW)
	{
		char *pwszBuf=sm_get_pool_memory(PM_FNAME);
		make_win32_path_UTF8_2_wchar(&pwszBuf, file);

		h=p_FindFirstFileW((LPCWSTR)pwszBuf, &info_w);
		sm_free_pool_memory(pwszBuf);

		pdwFileAttributes=&info_w.dwFileAttributes;
		pdwReserved0     =&info_w.dwReserved0;
		pnFileSizeHigh   =&info_w.nFileSizeHigh;
		pnFileSizeLow    =&info_w.nFileSizeLow;
		pftLastAccessTime=&info_w.ftLastAccessTime;
		pftLastWriteTime =&info_w.ftLastWriteTime;
		pftCreationTime  =&info_w.ftCreationTime;
		// use ASCII
	}
	else if (p_FindFirstFileA)
	{
		h=p_FindFirstFileA(file, &info_a);

		pdwFileAttributes=&info_a.dwFileAttributes;
		pdwReserved0     =&info_a.dwReserved0;
		pnFileSizeHigh   =&info_a.nFileSizeHigh;
		pnFileSizeLow    =&info_a.nFileSizeLow;
		pftLastAccessTime=&info_a.ftLastAccessTime;
		pftLastWriteTime =&info_a.ftLastWriteTime;
		pftCreationTime  =&info_a.ftCreationTime;
	}

	if(h==INVALID_HANDLE_VALUE)
	{
		const char *err = errorString();
		/* Note, in creating leading paths, it is normal that
		   the file does not exist. */
		LocalFree((void *)err);
		errno=b_errno_win32;
		return -1;
	}
	else
		FindClose(h);

	*winattr=(int64_t)*pdwFileAttributes;

	/* Graham says: all the following stuff seems rather complicated.
	   It is probably not all needed anymore, since I have added *winattr
	   above, which bacula did not do.
	   One reason for keeping it is that some of the values get converted
	   to unix-style permissions that show up in the long list
	   functionality.
	   I think I would prefer to remove it all at some point. */

	sb->st_mode = 0777;  // start with everything
	if(*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
		sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
	if(*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
		sb->st_mode &= ~S_IRWXO; // remove everything for other
	if(*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
		sb->st_mode |= S_ISVTX; // use sticky bit -> hidden
	sb->st_mode |= S_IFDIR;

	/* Store reparse/mount point info in st_rdev.  Note a
	   Win32 reparse point (junction point) is like a link
	   though it can have many properties (directory link,
	   soft link, hard link, HSM, ...
	   A mount point is a reparse point where another volume
	   is mounted, so it is like a Unix mount point (change of
	   filesystem).  */
	if(*pdwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
		sb->st_rdev=WIN32_MOUNT_POINT;
	else
		sb->st_rdev=0;

	if((*pdwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
	  && (*pdwReserved0 & IO_REPARSE_TAG_MOUNT_POINT))
	{
		sb->st_rdev=WIN32_MOUNT_POINT;
		/* Now to find out if the directory is a mount point or
		   a reparse point, we must do a song and a dance.
		   Explicitly open the file to read the reparse point, then
		   call DeviceIoControl to find out if it points to a Volume
		   or to a directory. */
		h=INVALID_HANDLE_VALUE;
		if(p_GetFileAttributesW)
		{
			char *pwszBuf=sm_get_pool_memory(PM_FNAME);
			make_win32_path_UTF8_2_wchar(&pwszBuf, file);
			if(p_CreateFileW)
			{
				h=CreateFileW((LPCWSTR)pwszBuf, GENERIC_READ,
					FILE_SHARE_READ, NULL, OPEN_EXISTING,
					FILE_FLAG_BACKUP_SEMANTICS
					| FILE_FLAG_OPEN_REPARSE_POINT,
					NULL);
			}
			sm_free_pool_memory(pwszBuf);
		}
		else if(p_GetFileAttributesA)
		{
			h=CreateFileA(file, GENERIC_READ,
				FILE_SHARE_READ, NULL, OPEN_EXISTING,
				FILE_FLAG_BACKUP_SEMANTICS
				| FILE_FLAG_OPEN_REPARSE_POINT,
				NULL);
		}
		if(h!=INVALID_HANDLE_VALUE)
		{
			char dummy[1000];
			REPARSE_DATA_BUFFER *rdb=(REPARSE_DATA_BUFFER *)dummy;
			rdb->ReparseTag=IO_REPARSE_TAG_MOUNT_POINT;
			DWORD bytes;
			bool ok;
			ok=DeviceIoControl(h, FSCTL_GET_REPARSE_POINT,
				NULL, 0, // in buffer, bytes
				(LPVOID)rdb,
				(DWORD)sizeof(dummy), // out buffer, btyes
				(LPDWORD)&bytes, (LPOVERLAPPED)0);
			if(ok)
			{
				char *utf8=sm_get_pool_memory(PM_NAME);
				wchar_2_UTF8(utf8, (wchar_t *)
				  rdb->SymbolicLinkReparseBuffer.PathBuffer);
				if(!strncasecmp(utf8, "\\??\\volume{", 11))
					sb->st_rdev=WIN32_MOUNT_POINT;
				else // Points to a directory so we ignore it. 
					sb->st_rdev=WIN32_JUNCTION_POINT;
				sm_free_pool_memory(utf8);
			}
			CloseHandle(h);
		}
	}
	sb->st_size=*pnFileSizeHigh;
	sb->st_size<<=32;
	sb->st_size|=*pnFileSizeLow;
	sb->st_blksize=4096;
	sb->st_blocks=(uint32_t)(sb->st_size+4095)/4096;

	sb->st_atime=cvt_ftime_to_utime(*pftLastAccessTime);
	sb->st_mtime=cvt_ftime_to_utime(*pftLastWriteTime);
	sb->st_ctime=cvt_ftime_to_utime(*pftCreationTime);

	return 0;
}
Exemple #23
0
static void FindFiles(std::vector<std::string>& matches, const std::string& datadir, const std::string& dir, const boost::regex &regexpattern, int flags)
{
#ifdef _WIN32
    WIN32_FIND_DATA wfd;
    HANDLE hFind = FindFirstFile((datadir + dir + "\\*").c_str(), &wfd);

    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            if(strcmp(wfd.cFileName,".") && strcmp(wfd.cFileName ,"..")) {
                if(!(wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) {
                    if ((flags & FileSystem::ONLY_DIRS) == 0) {
                        if (boost::regex_match(wfd.cFileName, regexpattern)) {
                            matches.push_back(dir + wfd.cFileName);
                        }
                    }
                } else {
                    if (flags & FileSystem::INCLUDE_DIRS) {
                        if (boost::regex_match(wfd.cFileName, regexpattern)) {
                            matches.push_back(dir + wfd.cFileName + "\\");
                        }
                    }
                    if (flags & FileSystem::RECURSE) {
                        FindFiles(matches, datadir, dir + wfd.cFileName + "\\", regexpattern, flags);
                    }
                }
            }
        } while (FindNextFile(hFind, &wfd));
        FindClose(hFind);
    }
#else
    DIR* dp;
    struct dirent* ep;

    if (!(dp = opendir((datadir + dir).c_str()))) {
        return;
    }

    while ((ep = readdir(dp))) {
        // exclude hidden files
        if (ep->d_name[0] != '.') {
            // is it a file? (we just treat sockets / pipes / fifos / character&block devices as files...)
            // (need to stat because d_type is DT_UNKNOWN on linux :-/)
            struct stat info;
            if (stat((datadir + dir + ep->d_name).c_str(), &info) == 0) {
                if (!S_ISDIR(info.st_mode)) {
                    if ((flags & FileSystem::ONLY_DIRS) == 0) {
                        if (boost::regex_match(ep->d_name, regexpattern)) {
                            matches.push_back(dir + ep->d_name);
                        }
                    }
                } else {
                    // or a directory?
                    if (flags & FileSystem::INCLUDE_DIRS) {
                        if (boost::regex_match(ep->d_name, regexpattern)) {
                            matches.push_back(dir + ep->d_name + "/");
                        }
                    }
                    if (flags & FileSystem::RECURSE) {
                        FindFiles(matches, datadir, dir + ep->d_name + "/", regexpattern, flags);
                    }
                }
            }
        }
    }
    closedir(dp);
#endif
}
int Remerge()
{
    int i;
    char pszInstallDir[MAX_PATH];
    char pszKadName[MAX_PATH];
    char pszOrigKadName[MAX_PATH];
    char pszBackKadName[MAX_PATH];
    char pszAddKAD[MAX_PATH];
    char pszAddKADFullPath[MAX_PATH];
    char pszLogFile[MAX_PATH];
    char pszFindFilePattern[MAX_PATH];
    BOOL bError = FALSE;

    // hack fill with something: KAD merge Dll test for strlen of parameter
    for(i=0; i<MAX_PATH; i++)
    {
        pszInstallDir[i] = 1;
    }
    pszInstallDir[MAX_PATH-1] = 0;
    if (Get4CPath(pszInstallDir)!=TRUE)
    {
        printf("Error: Looking up ATCMControl installation path!\n");
        return -1;
    }


    // ************************ 4ceng.kad  *************************
    strcpy(pszOrigKadName, pszInstallDir);
    strcat(pszOrigKadName, "Engineering\\bin\\4ceng.kad");
    
    strcpy(pszBackKadName, pszOrigKadName);
    strcat(pszBackKadName, ".back");

    DeleteFile(pszBackKadName);
    if (!MoveFile(pszOrigKadName, pszBackKadName))
    {
        printf("Could not create backup of 4ceng.kad\n");
    }

    printf("Merging 4ceng.kad\n");

    strcpy(pszKadName, "Engineering\\bin\\4ceng.kad");
    strcpy(pszLogFile, "KadMerge.log");


    HANDLE hFind;
    WIN32_FIND_DATA findFileData;
    BOOL bFound = TRUE;

    strcpy(pszFindFilePattern, pszInstallDir);
    strcat(pszFindFilePattern, "Engineering\\bin\\*_4ceng.kad");


    // start with Kernel_IEC_4ceng.kad and skip this later
    strcpy(pszAddKAD, "Kernel_IEC_4ceng.kad");
    strcpy(pszAddKADFullPath, pszInstallDir);
    strcat(pszAddKADFullPath, "Engineering\\bin\\");
    strcat(pszAddKADFullPath, pszAddKAD);
    printf("Merging KAD: %s\n", pszAddKAD);
    if (MergeKAD_KnieFK(pszInstallDir, 
                         pszKadName, 
                         pszAddKADFullPath, 
                         TRUE, 
                         pszLogFile, 
                         FALSE)  != TRUE)
    {
        printf("Error: Merging KAD %s!\n", pszAddKAD);
        bError = TRUE;
    }
  
    hFind = FindFirstFile(pszFindFilePattern, &findFileData);

    if (hFind != INVALID_HANDLE_VALUE)
    {
        while (bFound)
        {
            strcpy(pszAddKAD, findFileData.cFileName);

            if (stricmp(pszAddKAD, "Kernel_IEC_4ceng.kad")!=0)
            {
                strcpy(pszAddKADFullPath, pszInstallDir);
                strcat(pszAddKADFullPath, "Engineering\\bin\\");
                strcat(pszAddKADFullPath, pszAddKAD);
                printf("Merging KAD: %s\n", pszAddKAD);
                if (MergeKAD_KnieFK(pszInstallDir, 
                                     pszKadName, 
                                     pszAddKADFullPath, 
                                     TRUE, 
                                     pszLogFile, 
                                     FALSE)  != TRUE)
                {
                    printf("Error: Merging KAD %s!\n", pszAddKAD);
                    bError = TRUE;
                }
            }
            bFound = FindNextFile(hFind, &findFileData);
        }
        FindClose(hFind);
    }



    // ************************ 4cg.kad  *************************
    strcpy(pszOrigKadName, pszInstallDir);
    strcat(pszOrigKadName, "Engineering\\bin\\4cg.kad");
    
    strcpy(pszBackKadName, pszOrigKadName);
    strcat(pszBackKadName, ".back");

    DeleteFile(pszBackKadName);
    if (!MoveFile(pszOrigKadName, pszBackKadName))
    {
        printf("Could not create backup of 4ceng.kad\n");
    }

    printf("\nRemerging 4cg.kad\n");

    strcpy(pszKadName, "Engineering\\bin\\4cg.kad");
    strcpy(pszLogFile, "KadMerge_CG.log");


    bFound = TRUE;

    strcpy(pszFindFilePattern, pszInstallDir);
    strcat(pszFindFilePattern, "Engineering\\bin\\*_4cg.kad");
  
    hFind = FindFirstFile(pszFindFilePattern, &findFileData);

    if (hFind != INVALID_HANDLE_VALUE)
    {
        while (bFound)
        {
            strcpy(pszAddKAD, findFileData.cFileName);

            strcpy(pszAddKADFullPath, pszInstallDir);
            strcat(pszAddKADFullPath, "Engineering\\bin\\");
            strcat(pszAddKADFullPath, pszAddKAD);
            printf("Merging KAD: %s\n", pszAddKAD);
            if (MergeKAD_KnieFK(pszInstallDir, 
                                 pszKadName, 
                                 pszAddKADFullPath, 
                                 TRUE, 
                                 pszLogFile, 
                                 FALSE)  != TRUE)
            {
                printf("Error: Merging KAD %s!\n", pszAddKAD);
                bError = TRUE;
            }
            bFound = FindNextFile(hFind, &findFileData);
        }
        FindClose(hFind);
    }

    printf("\n");
    if (bError)
    {
        printf("*************\n"
               " Errors during KAD remerging,\n"
               " the old KAD files are still available (4cg|4ceng).kad.back,\n"
               " please rename to original file names.\n\n");
    }
    else
    {
        printf("KADs successfully remerged!\n");
    }
    printf("\n");

    return 0;
}
Exemple #25
0
//------------------------------------------------------------------------
const char *rlFindFile(const char *pattern, int *context)
{
  static char freturn[512];

#ifdef RLUNIX
  static DIR *dirp;
  static struct dirent *dp;

  if(*context == 0) dirp = opendir(".");
  *context = 1;

  while((dp = readdir(dirp)) != NULL)
  {
    if(dp->d_name[0] == '.') ;
    else if(strstr(dp->d_name,pattern) != NULL)
    {
      strcpy(freturn,dp->d_name);
      return freturn;
    }
  }
  closedir(dirp);
  return NULL;
#endif

#ifdef __VMS
  int i,ret;
  static char file[512] = "";
  static char wildcard[80];
  struct dsc$descriptor_s dwildcard;
  struct dsc$descriptor_s dfreturn;

  strcpy(wildcard,pattern);

  dwildcard.dsc$w_length  = strlen(wildcard);
  dwildcard.dsc$a_pointer = wildcard;
  dwildcard.dsc$b_dtype   = DSC$K_DTYPE_T;
  dwildcard.dsc$b_class   = DSC$K_CLASS_S;

  dfreturn.dsc$w_length  = sizeof(freturn);
  dfreturn.dsc$a_pointer = &freturn[0];
  dfreturn.dsc$b_dtype   = DSC$K_DTYPE_T;
  dfreturn.dsc$b_class   = DSC$K_CLASS_S;

  ret = LIB$FIND_FILE(&dwildcard,&dfreturn,context,0,0,0,0);
  if     (ret == RMS$_NMF)    return NULL; // no more files found
  else if(ret != RMS$_NORMAL) return NULL;
  else if(strcmp(freturn,file) == 0) { file[0] = '\0'; return NULL; }
  i=0;
  while(freturn[i] > ' ')i++;
  freturn[i] = '\0';
  return freturn;
#endif

#ifdef RLWIN32
  static WIN32_FIND_DATA wfd;
  static HANDLE hFindFile;

  if(*context == 0) // find first
  {
    *context = 1;
    hFindFile = FindFirstFile(pattern,&wfd);
    if(hFindFile == INVALID_HANDLE_VALUE)    return NULL;
    else                                     strcpy(freturn,(const char *) &wfd.cFileName);
  }
  else // subsequent find
  {
    if(FindNextFile(hFindFile,&wfd) == TRUE) strcpy(freturn,(const char *) &wfd.cFileName);
    else                                   { FindClose(hFindFile); return NULL; }
  }
  return freturn;
#endif
}
Exemple #26
0
static bool tmpSearchPath(std::string  path, std::vector<zs_ut_s::_FileInfo> & files)
{
	if (path.length() == 0)
	{
		return false;
	}
	zsummer::utility::FixPath(path);

#ifdef WIN32
	WIN32_FIND_DATAA fd;
	std::string findpath = path;
	findpath.append("*");
	HANDLE hFile = FindFirstFileA(findpath.c_str(), &fd);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		return false;
	}
	zs_ut_s::_FileInfo file;
	do 
	{
		if (fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
		{
			if (strcmp(fd.cFileName, ".") != 0 && strcmp(fd.cFileName, "..") != 0 )
			{
				memset(&file, 0, sizeof(file));
				file.bDir = true;
				strcpy_s(file.filename, sizeof(file.filename), fd.cFileName);
				sprintf(file.fullpath, "%s%s", path.c_str(), fd.cFileName);
				files.push_back(file);
				tmpSearchPath(file.fullpath, files);
			}
		}
		else
		{
			memset(&file, 0, sizeof(file));
			file.bDir = false;
			file.filesize = fd.nFileSizeHigh;
			file.filesize = file.filesize << 32;
			file.filesize += fd.nFileSizeLow;
			strcpy_s(file.filename, sizeof(file.filename), fd.cFileName);
			sprintf(file.fullpath, "%s%s", path.c_str(), fd.cFileName);
			files.push_back(file);
		}
	} while (FindNextFileA(hFile, &fd));
	FindClose(hFile);

#else
	DIR *dp;
	struct dirent *entry;
	struct stat statbuf;
	if((dp = opendir(path.c_str())) == NULL) 
	{
		return false;
	}
	zs_ut_s::_FileInfo file;
	while((entry = readdir(dp)) != NULL) 
	{
		lstat(entry->d_name,&statbuf);
		if(S_ISDIR(statbuf.st_mode)) 
		{
			if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
			{
				continue;
			}
			memset(&file, 0, sizeof(file));
			file.bDir = true;
			file.filesize = statbuf.st_size;
			strcpy(file.filename, entry->d_name);
			sprintf(file.fullpath, "%s%s", path.c_str(), entry->d_name);
			files.push_back(file);
			tmpSearchPath(file.fullpath, files);
		}
		else 
		{
			memset(&file, 0, sizeof(file));
			file.bDir = false;
			file.filesize = statbuf.st_size;
			strcpy(file.filename, entry->d_name);
			file.fullpath[0] = '\0';
			files.push_back(file);
		}
	}
	closedir(dp);
#endif
	return true;
}
Exemple #27
0
bool DTXDirReportHandler(const char* inputdir, FILE *pOutFile, bool CommaDelim)
{
	char InputDir[_MAX_PATH];
	strcpy(InputDir, inputdir);

	int inputLen = strlen(InputDir);
	if (inputLen  == 0)
	{
		printf("\nError: invalid input directory \"%s\"", InputDir);
		return false;
	}

	if (InputDir[inputLen - 1] != '\\')
	{
		InputDir[inputLen] 		= '\\';
		InputDir[inputLen + 1] 	= 0;
		inputLen++;
	}

	// Loop over all .dtx files in input directory and child directories.
	WIN32_FIND_DATA findData;
	HANDLE findHandle;

	CString startDir = InputDir;
	startDir += "*.*";

	findHandle = FindFirstFile( LPCTSTR(startDir), &findData );
	if (findHandle != INVALID_HANDLE_VALUE)
	{
		do
		{
			if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				// Ignore directories starting with '.'
				if (findData.cFileName[0] != '.')
				{
					// Found a directory, recurse into it.
					CString newInDir = InputDir;
					newInDir += findData.cFileName;

					DTXDirReportHandler(newInDir, pOutFile, CommaDelim);
				}
			}
			else
			{
				// It's a file, check to see if it's a dtx.
				char ext[_MAX_EXT];
				char file[_MAX_FNAME];

				_splitpath(findData.cFileName, NULL, NULL, file, ext);

				// make sure the extension is lower case
				for (unsigned i = 0; i < strlen(ext); i++)
				{
					if (isupper(ext[i]))
					{
						ext[i] = tolower(ext[i]);
					}
				}

				// Found a DTX file, process it.
				if (!strcmp(ext, ".dtx"))
				{
					CString inFile = InputDir;
					inFile += file;
					inFile += ext;

					DTXReport(inFile, pOutFile, CommaDelim);
				}
			}
		}
		while (FindNextFile(findHandle, &findData));

		FindClose(findHandle);
	}

	return true;
}
Exemple #28
0
BOOL PASCAL CFile::GetStatus(LPCTSTR lpszFileName, CFileStatus& rStatus)
{
	ASSERT( lpszFileName != NULL );

	if ( lpszFileName == NULL ) 
	{
		return FALSE;
	}

	if ( lstrlen(lpszFileName) >= _MAX_PATH )
	{
		ASSERT(FALSE); // MFC requires paths with length < _MAX_PATH
		return FALSE;
	}
	
	// attempt to fully qualify path first
	if (!AfxFullPath(rStatus.m_szFullName, lpszFileName))
	{
		rStatus.m_szFullName[0] = '\0';
		return FALSE;
	}

	WIN32_FIND_DATA findFileData;
	HANDLE hFind = FindFirstFile((LPTSTR)lpszFileName, &findFileData);
	if (hFind == INVALID_HANDLE_VALUE)
		return FALSE;
	VERIFY(FindClose(hFind));

	// strip attribute of NORMAL bit, our API doesn't have a "normal" bit.
	rStatus.m_attribute = (BYTE)
		(findFileData.dwFileAttributes & ~FILE_ATTRIBUTE_NORMAL);

	// get just the low DWORD of the file size
	ASSERT(findFileData.nFileSizeHigh == 0);
	rStatus.m_size = (LONG)findFileData.nFileSizeLow;

	// convert times as appropriate
	if (CTime::IsValidFILETIME(findFileData.ftCreationTime))
	{
		rStatus.m_ctime = CTime(findFileData.ftCreationTime);
	}
	else
	{
		rStatus.m_ctime = CTime();
	}

	if (CTime::IsValidFILETIME(findFileData.ftLastAccessTime))
	{
		rStatus.m_atime = CTime(findFileData.ftLastAccessTime);
	}
	else
	{
		rStatus.m_atime = CTime();
	}

	if (CTime::IsValidFILETIME(findFileData.ftLastWriteTime))
	{
		rStatus.m_mtime = CTime(findFileData.ftLastWriteTime);
	}
	else
	{
		rStatus.m_mtime = CTime();
	}

	if (rStatus.m_ctime.GetTime() == 0)
		rStatus.m_ctime = rStatus.m_mtime;

	if (rStatus.m_atime.GetTime() == 0)
		rStatus.m_atime = rStatus.m_mtime;

	return TRUE;
}
Exemple #29
0
void DtxUtil::FillDTXHandler( const char* input, const char* output, char* command )
{
	char inputDir[_MAX_PATH];
	char outputDir[_MAX_PATH];

	strcpy( inputDir, input );
	strcpy( outputDir, output );

	int inputLen = strlen( inputDir );
	int outputLen = strlen( outputDir );

	if( !inputLen || !outputLen )
		return;

	if( inputDir[inputLen-1] != '\\' )
	{
		inputDir[inputLen] = '\\';
		inputDir[inputLen+1] = 0;
		inputLen++;
	}

	if( outputDir[outputLen-1] != '\\' )
	{
		outputDir[outputLen] = '\\';
		outputDir[outputLen+1] = 0;
		outputLen++;
	}

	// loop over all .tgas in input directory and child directories
	WIN32_FIND_DATA findData;
	HANDLE findHandle;
	CString startDir;

	startDir = inputDir;
	startDir += "*.*";
	findHandle = FindFirstFile( LPCTSTR(startDir), &findData );

	if( findHandle != INVALID_HANDLE_VALUE )
	{
		do
		{
			if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
			{
				// ignore directories starting with .
				if( findData.cFileName[0] != '.' )
				{
					// found a directory, recurse into it
					CString newInDir = inputDir;
					newInDir += findData.cFileName;
					CString newOutDir = outputDir;
					newOutDir += findData.cFileName;

					FillDTXHandler( newInDir, newOutDir, command );
				}
			}
			else
			{
				// it's a file, check to see if it's a tga
				char ext[_MAX_EXT];
				char file[_MAX_FNAME];

				_splitpath( findData.cFileName, NULL, NULL, file, ext );

				// make sure the extension is lower case
				for( unsigned i = 0; i < strlen( ext ); i++ )
				{
					if( isupper( ext[i] ) )
						ext[i] = tolower( ext[i] );
				}

				// found a tga, process it
				if( !strcmp( ext, ".tga" ) )
				{
					CString inFile = inputDir;
					inFile += file;
					inFile += ext;
					CString outFile = outputDir;
					outFile += file;
					outFile += ".dtx";

					FillDTX( inFile, outFile );
				}
			}
		}
		while( FindNextFile( findHandle, &findData ) );

		FindClose( findHandle );
	}
}
Exemple #30
0
/*
 * __wt_win_directory_list --
 *	Get a list of files from a directory, MSVC version.
 */
int
__wt_win_directory_list(WT_FILE_SYSTEM *file_system,
    WT_SESSION *wt_session, const char *directory,
    const char *prefix, char ***dirlistp, uint32_t *countp)
{
	DWORD windows_error;
	HANDLE findhandle;
	WIN32_FIND_DATAW finddata;
	WT_DECL_ITEM(pathbuf);
	WT_DECL_ITEM(file_utf8);
	WT_DECL_ITEM(pathbuf_wide);
	WT_DECL_ITEM(prefix_wide);
	WT_DECL_RET;
	WT_SESSION_IMPL *session;
	size_t dirallocsz, pathlen, prefix_widelen;
	uint32_t count;
	char *dir_copy, **entries;

	session = (WT_SESSION_IMPL *)wt_session;

	*dirlistp = NULL;
	*countp = 0;

	findhandle = INVALID_HANDLE_VALUE;
	dirallocsz = 0;
	entries = NULL;

	WT_ERR(__wt_strdup(session, directory, &dir_copy));
	pathlen = strlen(dir_copy);
	if (dir_copy[pathlen - 1] == '\\')
		dir_copy[pathlen - 1] = '\0';
	WT_ERR(__wt_scr_alloc(session, pathlen + 3, &pathbuf));
	WT_ERR(__wt_buf_fmt(session, pathbuf, "%s\\*", dir_copy));

	WT_ERR(__wt_to_utf16_string(session, pathbuf->data, &pathbuf_wide));
	WT_ERR(__wt_to_utf16_string(session, prefix, &prefix_wide));
	prefix_widelen = wcslen(prefix_wide->data);

	findhandle = FindFirstFileW(pathbuf_wide->data, &finddata);
	if (findhandle == INVALID_HANDLE_VALUE) {
		windows_error = __wt_getlasterror();
		__wt_errx(session,
		    "%s: directory-list: FindFirstFile: %s",
		    pathbuf->data, __wt_formatmessage(session, windows_error));
		WT_ERR(__wt_map_windows_error(windows_error));
	}

	count = 0;
	do {
		/*
		 * Skip . and ..
		 */
		if (wcscmp(finddata.cFileName, L".") == 0 ||
		    wcscmp(finddata.cFileName, L"..") == 0)
			continue;

		/* The list of files is optionally filtered by a prefix. */
		if (prefix != NULL &&
		    wcsncmp(finddata.cFileName, prefix_wide->data,
			prefix_widelen) != 0)
			continue;

		WT_ERR(__wt_realloc_def(
		    session, &dirallocsz, count + 1, &entries));

		WT_ERR(__wt_to_utf8_string(
		    session, finddata.cFileName, &file_utf8));
		WT_ERR(__wt_strdup(session, file_utf8->data, &entries[count]));
		++count;
		__wt_scr_free(session, &file_utf8);
	} while (FindNextFileW(findhandle, &finddata) != 0);

	*dirlistp = entries;
	*countp = count;

err:	if (findhandle != INVALID_HANDLE_VALUE)
		if (FindClose(findhandle) == 0) {
			windows_error = __wt_getlasterror();
			__wt_errx(session,
			    "%s: directory-list: FindClose: %s",
			    pathbuf->data,
			    __wt_formatmessage(session, windows_error));
			if (ret == 0)
				ret = __wt_map_windows_error(windows_error);
		}

	__wt_free(session, dir_copy);
	__wt_scr_free(session, &pathbuf);
	__wt_scr_free(session, &file_utf8);
	__wt_scr_free(session, &pathbuf_wide);
	__wt_scr_free(session, &prefix_wide);

	if (ret == 0)
		return (0);

	WT_TRET(__wt_win_directory_list_free(
	    file_system, wt_session, entries, count));

	WT_RET_MSG(session, ret,
	    "%s: directory-list, prefix \"%s\"",
	    directory, prefix == NULL ? "" : prefix);
}