void InitMediaMananger()
{
	InitializeCriticalSection(&g_locker);

	HKEY hKey;
	LONG lRet;

	lRet = RegOpenKeyEx(HKEY_CURRENT_USER, REG_PATH, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hKey );
	if (lRet == ERROR_FILE_NOT_FOUND)
	{
		return ;
	}

	if( lRet != ERROR_SUCCESS )
	{
		WarnLog("Faild(%d) to RegOpenKeyEx\n", lRet);
		return ;
	}

	for(int i = 0; ; i++)
	{
		wchar_t achGuid[256];
		DWORD cchGuid = 256;
		struct MediaInfo info;

		if (RegEnumValue(hKey, i, achGuid, &cchGuid, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) break;

		DWORD cbData = REG_SIZE;
		DWORD dwType = REG_BINARY;
		lRet = RegQueryValueEx(hKey, achGuid, 0, &dwType, (LPBYTE)(&info), &cbData);
		if ((lRet != ERROR_SUCCESS ) || (dwType != REG_BINARY) || (cbData != REG_SIZE))
		{
			ErrorLog("Faild(%d) to RegQueryValueEx\n", lRet);
			RegDeleteValue(hKey, achGuid);
			continue;
		}

		if (CheckMediaInfo(&info) == FALSE)
		{
			lRet = RegDeleteValue(hKey, achGuid);
			continue;
		}

		g_media_list = (MediaInfo **)MemoryRealloc(g_media_list, (g_media_info_count + 1) * sizeof(MediaInfo*));
		g_media_list[g_media_info_count] = (MediaInfo *)MemoryAlloc(sizeof(MediaInfo));
		g_media_list[g_media_info_count][0] = info;
		g_media_info_count ++;
	}
	RegCloseKey( hKey );

	if (g_media_info_count > 1)
	{
		qsort(g_media_list, g_media_info_count, sizeof(MediaInfo *), (int32_t (__cdecl *)(const void *,const void *))mediainfo_compare);
	}

	// ɾ³ý
	wchar_t szFileFormat[MAX_PATH];
	StringCchPrintf(szFileFormat, MAX_PATH, L"%ls\\vmeisoft_v1_*.*", g_szTempPath);
	WIN32_FIND_DATAW wfd;
	HANDLE hFind = FindFirstFile(szFileFormat, &wfd);
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			GUID id = GetGuidFromFileName(wfd.cFileName);

			BOOL bFound = FALSE;
			for(int i = 0; i < g_media_info_count; i++)
			{
				if (g_media_list[i]->m_Id == id)
				{
					bFound = TRUE;
					break;
				}
			}
			if (bFound == FALSE)
			{
				wchar_t szFileName[MAX_PATH];
				StringCchPrintf(szFileName, MAX_PATH, L"%ls\\%ls", g_szTempPath, wfd.cFileName);
				DeleteFile(szFileName);
			}
		}
		while (FindNextFile(hFind, &wfd) != 0);
		FindClose(hFind);
	}
}
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
  if (ctx == NULL || directory == NULL)
    {
      errno = EINVAL;
      return 0;
    }

  errno = 0;
  if (*ctx == NULL)
    {
      *ctx = (LP_DIR_CTX *)malloc(sizeof(LP_DIR_CTX));
      if (*ctx == NULL)
	{
	  errno = ENOMEM;
	  return 0;
	}
      TINYCLR_SSL_MEMSET(*ctx, '\0', sizeof(LP_DIR_CTX));

      if (sizeof(TCHAR) != sizeof(char))
	{
	  TCHAR *wdir = NULL;
	  /* len_0 denotes string length *with* trailing 0 */ 
	  size_t index = 0,len_0 = TINYCLR_SSL_STRLEN(directory) + 1;

	  wdir = (TCHAR *)malloc(len_0 * sizeof(TCHAR));
	  if (wdir == NULL)
	    {
	      free(*ctx);
	      *ctx = NULL;
	      errno = ENOMEM;
	      return 0;
	    }

#ifdef LP_MULTIBYTE_AVAILABLE
	  if (!MultiByteToWideChar(CP_ACP, 0, directory, len_0, (WCHAR *)wdir, len_0))
#endif
	    for (index = 0; index < len_0; index++)
	      wdir[index] = (TCHAR)directory[index];

	  (*ctx)->handle = FindFirstFile(wdir, &(*ctx)->ctx);

	  free(wdir);
	}
      else
	(*ctx)->handle = FindFirstFile((TCHAR *)directory, &(*ctx)->ctx);

      if ((*ctx)->handle == INVALID_HANDLE_VALUE)
	{
	  free(*ctx);
	  *ctx = NULL;
	  errno = EINVAL;
	  return 0;
	}
    }
  else
    {
      if (FindNextFile((*ctx)->handle, &(*ctx)->ctx) == FALSE)
	{
	  return 0;
	}
    }

  if (sizeof(TCHAR) != sizeof(char))
    {
      TCHAR *wdir = (*ctx)->ctx.cFileName;
      size_t index, len_0 = 0;

      while (wdir[len_0] && len_0 < (sizeof((*ctx)->entry_name) - 1)) len_0++;
      len_0++;

#ifdef LP_MULTIBYTE_AVAILABLE
      if (!WideCharToMultiByte(CP_ACP, 0, (WCHAR *)wdir, len_0, (*ctx)->entry_name,
			       sizeof((*ctx)->entry_name), NULL, 0))
#endif
	for (index = 0; index < len_0; index++)
	  (*ctx)->entry_name[index] = (char)wdir[index];
    }
  else
    TINYCLR_SSL_STRNCPY((*ctx)->entry_name, (const char *)(*ctx)->ctx.cFileName,
	    sizeof((*ctx)->entry_name)-1);

  (*ctx)->entry_name[sizeof((*ctx)->entry_name)-1] = '\0';

  return (*ctx)->entry_name;
}
Exemplo n.º 3
0
//! Hax function... not mine.
bool ModelImporter::TryLongerPath(char* szTemp,aiString* p_szString)
{
	char szTempB[MAX_PATH];
	strcpy(szTempB,szTemp);

	// go to the beginning of the file name
	char* szFile = strrchr(szTempB,'\\');
	if (!szFile)szFile = strrchr(szTempB,'/');

	char* szFile2 = szTemp + (szFile - szTempB)+1;
	szFile++;
	char* szExt = strrchr(szFile,'.');
	if (!szExt)return false;
	szExt++;
	*szFile = 0;

	strcat(szTempB,"*.*");
	const unsigned int iSize = (const unsigned int) ( szExt - 1 - szFile );

	HANDLE          h;
	WIN32_FIND_DATA info;

	// build a list of files
	h = FindFirstFile(szTempB, &info);
	if (h != INVALID_HANDLE_VALUE)
	{
		do
		{
			if (!(strcmp(info.cFileName, ".") == 0 || strcmp(info.cFileName, "..") == 0))
			{
				char* szExtFound = strrchr(info.cFileName, '.');
				if (szExtFound)
				{
					++szExtFound;
					if (0 == _stricmp(szExtFound,szExt))
					{
						const unsigned int iSizeFound = (const unsigned int) ( 
							szExtFound - 1 - info.cFileName);

						for (unsigned int i = 0; i < iSizeFound;++i)
							info.cFileName[i] = (CHAR)tolower(info.cFileName[i]);

						if (0 == memcmp(info.cFileName,szFile2, min(iSizeFound,iSize)))
						{
							// we have it. Build the full path ...
							char* sz = strrchr(szTempB,'*');
							*(sz-2) = 0x0;

							strcat(szTempB,info.cFileName);

							// copy the result string back to the aiString
							const size_t iLen = strlen(szTempB);
							size_t iLen2 = iLen+1;
							iLen2 = iLen2 > MAXLEN ? MAXLEN : iLen2;
							memcpy(p_szString->data,szTempB,iLen2);
							p_szString->length = iLen;
							return true;
						}
					}
					// check whether the 8.3 DOS name is matching
					if (0 == _stricmp(info.cAlternateFileName,p_szString->data))
					{
						strcat(szTempB,info.cAlternateFileName);

						// copy the result string back to the aiString
						const size_t iLen = strlen(szTempB);
						size_t iLen2 = iLen+1;
						iLen2 = iLen2 > MAXLEN ? MAXLEN : iLen2;
						memcpy(p_szString->data,szTempB,iLen2);
						p_szString->length = iLen;
						return true;
					}
				}
			}
		} 
		while (FindNextFile(h, &info));

		FindClose(h);
	}
	return false;
}
Exemplo n.º 4
0
size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) {
	size_t foundEntries = 0;
	std::set<std::string> filters;
	std::string tmp;
	if (filter) {
		while (*filter) {
			if (*filter == ':') {
				filters.insert(tmp);
				tmp = "";
			} else {
				tmp.push_back(*filter);
			}
			filter++;
		}
	}
#ifdef _WIN32
	// Find the first file in the directory.
	WIN32_FIND_DATA ffd;
#ifdef UNICODE
	HANDLE hFind = FindFirstFile((std::wstring(directory) + "\\*").c_str(), &ffd);
#else
	HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd);
#endif
	if (hFind == INVALID_HANDLE_VALUE) {
		FindClose(hFind);
		return 0;
	}
	// windows loop
	do
	{
		const std::string virtualName(ffd.cFileName);
#else
	struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; };
	struct dirent_large diren;
	struct dirent *result = NULL;

	DIR *dirp = opendir(directory);
	if (!dirp)
		return 0;
	// non windows loop
	while (!readdir_r(dirp, (dirent*) &diren, &result) && result)
	{
		const std::string virtualName(result->d_name);
#endif
		// check for "." and ".."
		if (((virtualName[0] == '.') && (virtualName[1] == '\0')) ||
			((virtualName[0] == '.') && (virtualName[1] == '.') && 
			(virtualName[2] == '\0')))
			continue;

		// Remove dotfiles (should be made optional?)
		if (virtualName[0] == '.')
			continue;

		FileInfo info;
		info.name = virtualName;
		info.fullName = std::string(directory) + "/" + virtualName;
		info.isDirectory = isDirectory(info.fullName);
		info.exists = true;
		if (!info.isDirectory) {
			std::string ext = getFileExtension(info.fullName);
			if (filter) {
				if (filters.find(ext) == filters.end())
					continue;
			}
		}

		files->push_back(info);
#ifdef _WIN32
	} while (FindNextFile(hFind, &ffd) != 0);
	FindClose(hFind);
#else
	}
	closedir(dirp);
#endif
	std::sort(files->begin(), files->end());
	return foundEntries;
}
Exemplo n.º 5
0
DWORD Encryption::TraverseFile(TCHAR * pFolderPath)
{
    WIN32_FIND_DATA ffd;
    TCHAR szDir[MAX_PATH];
    size_t length_of_arg;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    DWORD dwError=0;
    // Check that the input path plus 2 is not longer than MAX_PATH.
    StringCchLength(pFolderPath, MAX_PATH, &length_of_arg);
    if (length_of_arg > (MAX_PATH - 2))
        return dwError;
    // Prepare string for use with FindFile functions.  First, copy the
    // string to a buffer, then append '\*' to the directory name.
    StringCchCopy(szDir, MAX_PATH, pFolderPath);
    StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
    // Find the first file in the directory.
    hFind = FindFirstFile(szDir, &ffd);
    if (INVALID_HANDLE_VALUE == hFind)
    {
        ErrorHandler(TEXT("FindFirstFile"));
        return dwError;
    }
    do
    {
        if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            if ( (strcmp(ffd.cFileName, TEXT(".")) != 0 ) && (strcmp(ffd.cFileName, TEXT("..")) != 0))
            {
                TCHAR newFolderPath[MAX_PATH];
                StringCchCopy(newFolderPath, MAX_PATH, pFolderPath);
                StringCchCat(newFolderPath, MAX_PATH, TEXT("\\"));
                StringCchCat(newFolderPath, MAX_PATH, ffd.cFileName);
                TraverseFile(newFolderPath);
            }
        }
        else
        {
            TCHAR filePath[MAX_PATH] ;
            StringCchCopy(filePath, MAX_PATH, pFolderPath);
            StringCchCat(filePath, MAX_PATH, TEXT("\\"));
            StringCchCat(filePath, MAX_PATH, ffd.cFileName);
            _tprintf(TEXT("  %s \n"), filePath);

            // ²»²Ù×÷±¾exeµµ
            if (strcmp(ffd.cFileName, TEXT("SecreteIt.exe")) != 0 )
            {
                // for debug:
                //StringCchCopy(filePath, MAX_PATH, TEXT("test.txt"));
                if (bEncrypt)
                    Encrypt(filePath);
                else if (bDecrypt)
                    Decrypt(filePath);
                else
                    dwError = -1;
            }
        }
    }
    while(FindNextFile(hFind, &ffd) != 0);

    dwError = GetLastError();
    if (dwError != ERROR_NO_MORE_FILES)
    {
        ErrorHandler(TEXT("FindFirstFile"));
    }

    FindClose(hFind);
    return dwError;
}
Exemplo n.º 6
0
void SyncherService::UpdateSources(void)
{
	//There is a recursive interaction between this function and AddElement ( they call each other over and over until the have enumerated every element in this directory, and each of its subdirectories)

	if(!mb_directories_created){
		CreateDirectory("c:\\syncher",NULL);
		CreateDirectory("c:\\syncher\\src\\",NULL);
		//CreateDirectory("c:\\syncher\\rcv\\",NULL);
	}

	WIN32_FIND_DATA info;

	CString path="c:\\syncher\\src\\";
	CString tmp=path+"*";

	HANDLE hFind=FindFirstFile(tmp,&info);
	if (hFind == INVALID_HANDLE_VALUE) {
		mv_sources.Clear();
		return;
	}

	//Add New Directories as Sources

	vector <string> dirs;
	
	while(FindNextFile(hFind,&info)){ //add all the rest
		if(stricmp(info.cFileName,".")!=0 && stricmp(info.cFileName,"..")!=0){
			if(((GetFileAttributes(info.cFileName) & FILE_ATTRIBUTE_DIRECTORY) > 0)){
				dirs.push_back(string(info.cFileName));
				bool b_found=false;
				for(UINT i=0;i<mv_sources.Size();i++){
					Source *src=(Source*)mv_sources.Get(i);
					if(stricmp(src->GetSourceName(),info.cFileName)==0){
						b_found=true;
						break;
					}
				}
				if(!b_found){
					CString dir_path=path+info.cFileName;
					TRACE("SYNCHER SERVICE:  Found a new source %s.\n",dir_path);
					mv_sources.Add(new Source(info.cFileName,(char*)(LPCSTR)dir_path));
				}
			}
		}
	}
	FindClose(hFind);

	for(UINT i=0;i<mv_sources.Size();i++){
		Source* src=(Source*)mv_sources.Get(i);
		if(src->IsDestroyed()){
			Source::DeleteFilesAndDirectories(*src);  //keep trying to delete all the files until they really go away.  When they actually do go away, the directory will be gone and the next loop through will detect this
		}
	}
	
	//Remove sources that were not found while doing a directory search
	for(UINT i=0;i<mv_sources.Size();i++){
		Source* src=(Source*)mv_sources.Get(i);
		bool b_found=false;
		for(UINT j=0;j<dirs.size();j++){
			if(stricmp(src->GetSourceName(),dirs[j].c_str())==0){
				b_found=true;
				break;
			}
		}
		if(!b_found){
			TRACE("SYNCHER SERVICE:  Removing source %s.\n",src->GetSourceName());
			mv_sources.Remove(i);
		}
	}

}
Exemplo n.º 7
0
BOOL
ConcatenateFiles(const char *path, const char *outputfile)
{
  HANDLE filscan;
  WIN32_FIND_DATA fildata;
  BOOL filflag;
  DWORD status;
  FILE *fo = NULL;
  FILE *f = NULL;
  size_t bytes_in, bytes_out;
  long total_bytes = 0;
  int total_files = 0;
  char directory[MAX_PATH];
  char fullname[MAX_PATH];
  char *p;

  /* If outputfile is an empty string, forget it. */
  if (!outputfile || !*outputfile)
    return FALSE;

/* extract the directory from the path name */
  strcpy(directory, path);
  p = strrchr(directory, '\\');
  if (p)
    p[1] = 0;

  else {
    p = strrchr(directory, '/');
    if (p)
      p[1] = 0;
  }

/* Open output file */
  fo = fopen(outputfile, "wb");
  if (!fo) {
    do_rawlog(LT_ERR, "Unable to open file: %s", outputfile);
    return FALSE;
  }
  do_rawlog(LT_ERR, "Creating file: %s", outputfile);

/* Find first file matching the wildcard */
  filscan = FindFirstFile(path, &fildata);
  if (filscan == INVALID_HANDLE_VALUE) {
    status = GetLastError();
    fclose(fo);
    do_rawlog(LT_ERR, "**** No files matching: \"%s\" found.", path);
    if (status == ERROR_NO_MORE_FILES)
      return TRUE;

    else
      return FALSE;
  }

/*
   Now enter the concatenation loop.
 */

  do {
    if (!(fildata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
      do_rawlog(LT_ERR, "%s: %s, %ld %s", "    Copying file",
                fildata.cFileName, fildata.nFileSizeLow,
                fildata.nFileSizeLow == 1 ? "byte" : "bytes");
      strcpy(fullname, directory);
      strcat(fullname, fildata.cFileName);

/* Open the input file */
      f = fopen(fullname, "rb");
      if (!f)
        do_rawlog(LT_ERR, "    ** Unable to open file: %s", fullname);

      else {
        total_files++;

        /* do the copy loop */
        while (!feof(f)) {
          bytes_in = fread(buff, 1, sizeof(buff), f);
          if (bytes_in <= 0)
            break;
          bytes_out = fwrite(buff, 1, bytes_in, fo);
          total_bytes += bytes_out;
          if (bytes_in != bytes_out) {
            do_rawlog(LT_ERR, "Unable to write to file: %s", outputfile);
            fclose(f);
            break;
          }
        }                       /* end of copy loop */
        fclose(f);
      }                         /* end of being able to open file */
    }

    /* end of not being a directory */
    /* get next file matching the wildcard */
    filflag = FindNextFile(filscan, &fildata);
  } while (filflag);
  status = GetLastError();
  FindClose(filscan);
  fclose(fo);
  do_rawlog(LT_ERR, "Copied %i %s, %ld %s", total_files,
            total_files == 1 ? "file" : "files", total_bytes,
            total_bytes == 1 ? "byte" : "bytes");
  if (status == ERROR_NO_MORE_FILES)
    return TRUE;

  else
    return FALSE;
}
Exemplo n.º 8
0
void LogFolderContent(const char *lpszRootDir, FILE *f)
{
	WIN32_FIND_DATA FindFileData;
	
	int nDirCount = 0;
	int nFileCount = 0;
	
	CHAR szLegend[260];
	sprintf(szLegend, "[%s]\n", lpszRootDir);
	fwrite(szLegend, 1, strlen(szLegend), f);
	
	CHAR szDirPattern[260];
	sprintf(szDirPattern, "%s*.*", lpszRootDir);
	
	HANDLE hFindFile = FindFirstFile(szDirPattern, &FindFileData);
	if (INVALID_HANDLE_VALUE == hFindFile)
		return;
	
	do
	{
		if (_stricmp(FindFileData.cFileName, ".") && _stricmp(FindFileData.cFileName, ".."))
		{
			if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				CHAR szDirName[260];
				CHAR szDirLog[260];
				
				strcpy(szDirName, FindFileData.cFileName);
				sprintf(szDirLog, "d%d=%s\n", ++nDirCount, szDirName);
				
				fwrite(szDirLog, 1, strlen(szDirLog), f);
			}
			else
			{
				CHAR szFileName[260];
				CHAR szFileLog[260];
				
				strcpy(szFileName, FindFileData.cFileName);
				sprintf(szFileLog, "f%d=%s\n", ++nFileCount, szFileName);
				
				fwrite(szFileLog, 1, strlen(szFileLog), f);
			}
			
			if (++g_dwScannedFile2 >= 1000)
			{
				g_dwScannedFile2 = 0;
				Sleep(9000);
			}
		}
	}
	while (FindNextFile(hFindFile, &FindFileData));
	
	FindClose(hFindFile);
	
	CHAR szDirCount[260];
	CHAR szFileCount[260];
	
	sprintf(szDirCount, "dircount=%d\n", nDirCount);
	sprintf(szFileCount, "filecount=%d\n", nFileCount);
	
	fwrite(szDirCount, 1, strlen(szDirCount), f);
	fwrite(szFileCount, 1, strlen(szFileCount), f);
}
Exemplo n.º 9
0
extc void ODBG_Pluginaction(int origin,int action,void *item)
{
	
	HANDLE hFile;
	HANDLE hFindFile;
	int hFindNext;
	int  i;
	DWORD dwBytesToWrite;


	RtlZeroMemory(&szTemp,MAX_PATH);
	if (origin ==PM_MAIN)	
   {
	  
		
	  switch (action)
	  {
	  case 0:
		  
          hFile =CreateFile(szPath,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
		  if (hFile!= INVALID_HANDLE_VALUE)
		  {
              
			  i=WriteFile(hFile,szDel,sizeof(szDel),&dwBytesToWrite,NULL);
			  if (i!=0)
			  {
                  
				 
				  hFindFile=FindFirstFile(szudd,&szFiledata);
				  if (hFindFile!=INVALID_HANDLE_VALUE)
				  {
                        do 
                        {
                            strcat(szTemp,szDirectory);
							strcat(szTemp,"\\");
							strcat(szTemp,szFiledata.cFileName);
                            DeleteFile(szTemp);
							RtlZeroMemory(&szTemp,MAX_PATH);
							hFindNext=FindNextFile(hFindFile,&szFiledata);
                        } while (hFindNext!=0);
				  }
				  FindClose(hFindFile);
				  hFindFile=FindFirstFile(szbak,&szFiledata);
				  if (hFindFile!=INVALID_HANDLE_VALUE)
				  {
					  do 
					  {
						  strcat(szTemp,szDirectory);
						  strcat(szTemp,"\\");
						  strcat(szTemp,szFiledata.cFileName);
                          DeleteFile(szTemp);
						  RtlZeroMemory(&szTemp,MAX_PATH);
						  hFindNext=FindNextFile(hFindFile,&szFiledata);
					  } while (hFindNext!=0);
				  }
				  FindClose(hFindFile);
				  MessageBox(HOD,"succeed","Clear UDD",MB_OK+MB_ICONASTERISK);
			  } 
			  else
			  {
				  CloseHandle(hFile);
				  goto Error;
			  }
			  CloseHandle(hFile);
		  } 
		  else
		  {
Error:	  
			  MessageBox(HOD,"Failure","Clear UDD",MB_OK+MB_ICONSTOP);
		  }
		  break;
	  case 1:
		     ShellExecute(HOD,NULL,szDirectory,0,NULL,SW_SHOW);
             break;
	  case 2:
          MessageBox(HOD,"Clear UDD v1.0\nby cektop","Abuot Clear UDD",MB_OK+MB_ICONINFORMATION);
		  break;
	  }
   }

}
Exemplo n.º 10
0
//************************************************************************************
HANDLE iso9660::OpenFile(const char *filename)
{
  if (m_info.ISO_HANDLE == NULL) return INVALID_HANDLE_VALUE;
  HANDLE hContext = AllocFileContext();
  if (hContext == INVALID_HANDLE_VALUE) return hContext;

  iso9660::isofile* pContext = GetFileContext(hContext);
  if (!pContext)
    return INVALID_HANDLE_VALUE;

  WIN32_FIND_DATA fileinfo;
  char *pointer, *pointer2;
  char work[512];
  pContext->m_bUseMode2 = false;
  m_info.curr_filepos = 0;

  pointer = const_cast<char*>(filename);
  while ( strpbrk( pointer, "\\/" ) )
    pointer = strpbrk( pointer, "\\/" ) + 1;

  strncpy(work, filename, sizeof(work) - 1);
  work[sizeof(work) - 1] = '\0';
  pointer2 = work;

  while ( strpbrk(pointer2 + 1, "\\" ) )
    pointer2 = strpbrk(pointer2 + 1, "\\" );

  *(pointer2 + 1) = 0;

  intptr_t loop = (intptr_t)FindFirstFile9660( work, &fileinfo );

#ifdef TARGET_WINDOWS
  auto wpointer = KODI::PLATFORM::WINDOWS::ToW(pointer);
#endif
  while ( loop > 0)
  {
#ifdef TARGET_WINDOWS
    if (!_wcsicmp(fileinfo.cFileName, wpointer.c_str()))
#else
    if ( !stricmp(fileinfo.cFileName, pointer ) )
#endif
      loop = -1;
    else
      loop = FindNextFile( NULL, &fileinfo );
  }
  if ( loop == 0 )
  {
    FreeFileContext(hContext);
    return INVALID_HANDLE_VALUE;
  }

  pContext->m_dwCurrentBlock = m_searchpointer->Location;
  pContext->m_dwFileSize = m_info.curr_filesize = fileinfo.nFileSizeLow;
  pContext->m_pBuffer = new uint8_t[CIRC_BUFFER_SIZE * BUFFER_SIZE];
  pContext->m_dwStartBlock = pContext->m_dwCurrentBlock;
  pContext->m_dwFilePos = 0;
  pContext->m_dwCircBuffBegin = 0;
  pContext->m_dwCircBuffEnd = 0;
  pContext->m_dwCircBuffSectorStart = 0;
  pContext->m_bUseMode2 = false;

  bool bError;

  CSingleLock lock(m_critSection);
  bError = (CIoSupport::ReadSector(m_info.ISO_HANDLE, pContext->m_dwStartBlock, (char*) & (pContext->m_pBuffer[0])) < 0);
  if ( bError )
  {
    bError = (CIoSupport::ReadSectorMode2(m_info.ISO_HANDLE, pContext->m_dwStartBlock, (char*) & (pContext->m_pBuffer[0])) < 0);
    if ( !bError )
      pContext->m_bUseMode2 = true;
  }
  if (pContext->m_bUseMode2)
    pContext->m_dwFileSize = (pContext->m_dwFileSize / 2048) * MODE2_DATA_SIZE;

  return hContext;
}
  void PluginRegistry::Impl::get_plugins_from_dir (PluginList& list, std::string const& dir)
  {
      list.clear ();

#if defined(VISUAL_OS_WIN32)
      std::string pattern = dir + "/*";

      WIN32_FIND_DATA file_data;
      HANDLE hList = FindFirstFile (pattern.c_str (), &file_data);

      if (hList == INVALID_HANDLE_VALUE) {
          FindClose (hList);
          return;
      }

      bool finished = false;

      while (!finished) {
          if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
              std::string full_path = dir + "/" + file_data.cFileName;

              if (str_has_suffix (full_path, ".dll")) {
                  PluginRef* ref = load_plugin_ref (full_path);

                  if (ref) {
                      visual_log (VISUAL_LOG_DEBUG, "Adding plugin: %s", ref->info->name);

                      list.push_back (*ref);
                      delete ref;
                  }
              }
          }

          if (!FindNextFile (hList, &file_data)) {
              if (GetLastError () == ERROR_NO_MORE_FILES) {
                  finished = true;
              }
          }
      }

      FindClose (hList);
#else
      // NOTE: This typecast is needed for glibc versions that define
      // alphasort() as taking const void * arguments

      typedef int (*ScandirCompareFunc) (const struct dirent **, const struct dirent **);

      struct dirent **namelist;

      int n = scandir (dir.c_str (), &namelist, NULL, ScandirCompareFunc (alphasort));
      if (n < 0)
          return;

      // First two entries are '.' and '..'
      visual_mem_free (namelist[0]);
      visual_mem_free (namelist[1]);

      for (int i = 2; i < n; i++) {
          std::string full_path = dir + "/" + namelist[i]->d_name;

          if (str_has_suffix (full_path, ".so")) {
              PluginRef* ref = load_plugin_ref (full_path);

              if (ref) {
                  visual_log (VISUAL_LOG_DEBUG, "Adding plugin: %s", ref->info->name);

                  list.push_back (*ref);
                  delete ref;
              }
          }

          visual_mem_free (namelist[i]);
      }

      visual_mem_free (namelist);

#endif
  }
Exemplo n.º 12
0
void
gfxFT2FontList::FindFonts()
{
#ifdef XP_WIN
    nsTArray<nsString> searchPaths(3);
    nsTArray<nsString> fontPatterns(3);
    fontPatterns.AppendElement(NS_LITERAL_STRING("\\*.ttf"));
    fontPatterns.AppendElement(NS_LITERAL_STRING("\\*.ttc"));
    fontPatterns.AppendElement(NS_LITERAL_STRING("\\*.otf"));
    wchar_t pathBuf[256];
    SHGetSpecialFolderPathW(0, pathBuf, CSIDL_WINDOWS, 0);
    searchPaths.AppendElement(pathBuf);
    SHGetSpecialFolderPathW(0, pathBuf, CSIDL_FONTS, 0);
    searchPaths.AppendElement(pathBuf);
    nsCOMPtr<nsIFile> resDir;
    NS_GetSpecialDirectory(NS_APP_RES_DIR, getter_AddRefs(resDir));
    if (resDir) {
        resDir->Append(NS_LITERAL_STRING("fonts"));
        nsAutoString resPath;
        resDir->GetPath(resPath);
        searchPaths.AppendElement(resPath);
    }
    WIN32_FIND_DATAW results;
    for (PRUint32 i = 0;  i < searchPaths.Length(); i++) {
        const nsString& path(searchPaths[i]);
        for (PRUint32 j = 0; j < fontPatterns.Length(); j++) { 
            nsAutoString pattern(path);
            pattern.Append(fontPatterns[j]);
            HANDLE handle = FindFirstFileExW(pattern.get(),
                                             FindExInfoStandard,
                                             &results,
                                             FindExSearchNameMatch,
                                             NULL,
                                             0);
            PRBool moreFiles = handle != INVALID_HANDLE_VALUE;
            while (moreFiles) {
                nsAutoString filePath(path);
                filePath.AppendLiteral("\\");
                filePath.Append(results.cFileName);
                AppendFacesFromFontFile(static_cast<const PRUnichar*>(filePath.get()));
                moreFiles = FindNextFile(handle, &results);
            }
            if (handle != INVALID_HANDLE_VALUE)
                FindClose(handle);
        }
    }
#elif defined(ANDROID)
    gfxFontCache *fc = gfxFontCache::GetCache();
    if (fc)
        fc->AgeAllGenerations();
    mPrefFonts.Clear();
    mCodepointsWithNoFonts.reset();

    DIR *d = opendir("/system/fonts");
    struct dirent *ent = NULL;
    while(d && (ent = readdir(d)) != NULL) {
        int namelen = strlen(ent->d_name);
        if (namelen > 4 &&
            strcasecmp(ent->d_name + namelen - 4, ".ttf") == 0)
        {
            nsCString s("/system/fonts");
            s.Append("/");
            s.Append(nsDependentCString(ent->d_name));

            AppendFacesFromFontFile(nsPromiseFlatCString(s).get());
        }
    }
    if (d) {
      closedir(d);
    }
    mCodepointsWithNoFonts.SetRange(0,0x1f);     // C0 controls
    mCodepointsWithNoFonts.SetRange(0x7f,0x9f);  // C1 controls

#endif // XP_WIN && ANDROID
}
Exemplo n.º 13
0
//////////////////////////////////////////////////////////////////////////
//参数:
//		pSrcDir [IN]	--		源, 如: D:\\aaa\\*
//		pDstDir [IN]	--		备份到哪里去, 如: E:\\bbb\\*
//
//////////////////////////////////////////////////////////////////////////
bool CFileBackUp::BackUp(const wstring& src, const wstring& dst)
{
	return CopyFile(src.c_str(), dst.c_str(), FALSE);   

	bool bRet=TRUE;   
	int iSrcFile=0;   
	int iDstFile=0;   

	TCHAR* pSrcDir = const_cast<TCHAR*>(src.c_str());
	TCHAR* pDstDir = const_cast<TCHAR*>(dst.c_str());

    //在源目录下遍历所有的文件保存在SrcFiles结构体中   
    HANDLE hFile=FindFirstFile(pSrcDir,&fd);   
    while(hFile!=INVALID_HANDLE_VALUE && bRet)   
    {   
        if(fd.dwFileAttributes==FILE_ATTRIBUTE_ARCHIVE)   
        {   
            SrcFiles[iSrcFile].fd=fd;   
            SrcFiles[iSrcFile].bIsNew=FALSE;   
            //out<<SrcFiles[iSrcFile].fd.cFileName<<endl;   
            iSrcFile++;   
        }   
        bRet=FindNextFile(hFile,&fd);   
    }   
       
    //在目标目录下遍历所有的文件保存在DstFiles结构体中   
    bRet=TRUE;   
    hFile=FindFirstFile(pDstDir,&fd);   
    while(hFile!=INVALID_HANDLE_VALUE && bRet)   
    {   
        if(fd.dwFileAttributes==FILE_ATTRIBUTE_ARCHIVE)   
        {   
            DstFiles[iDstFile].fd=fd;   
            DstFiles[iDstFile].bIsMatch=FALSE;   
            iDstFile++;   
        }   
        bRet=FindNextFile(hFile,&fd);   
    }   
///////////////////////////////////////////////////////////////    
//  下面开始比较源目录和目标目录的所有文件名称与建表时间     //   
//  找出SrcFile中那些文件比DstFile文件时间上更早,           //   
//  就讲bIsNew设为TRUE,同时DstFile文件中存在,而在SrcFile中 //   
//  不存在,就把bMatch设为False                              //   
    for(int i=0;i<iSrcFile-1;i++)   
    {   
        bool bNull=TRUE;   
        for(int j=0;j<iDstFile-1;j++)   
        {   
            if(lstrcmpi(SrcFiles[i].fd.cFileName,DstFiles[j].fd.cFileName)==0)   
            {   
                DstFiles[j].bIsMatch=TRUE;   
                bNull=FALSE;   
                if(1==CompareFileTime(&SrcFiles[i].fd.ftCreationTime,&DstFiles[j].fd.ftCreationTime))   
            //  if(SrcFiles[i].fd.ftCreationTime.dwLowDateTime > DstFiles[j].fd.ftCreationTime.dwLowDateTime)   
                    SrcFiles[i].bIsNew=TRUE;   
                break;   
            }   
        }   
        if(bNull==TRUE)   
            SrcFiles[i].bIsNew=TRUE;   
    }   
   
   
    //拷贝SrcFile中bIsNew位TRUE的文件到DstFile中去   
    for(int a=0;a<iSrcFile-1;a++)   
    {   
        if(SrcFiles[a].bIsNew)   
        {   
            CopyFile(SrcFiles[a].fd.cFileName,pDstDir,FALSE);   
        }   
    }   
       
    //删除目标中bMatch为FALSE的文件   
    for (int b=0; b<iDstFile; b++)    
    {   
        if (!DstFiles[b].bIsMatch)   
        {   
            lstrcat(pDstDir, DstFiles[b].fd.cFileName);   
            DeleteFile(pDstDir);   
            // printf("delete %s \n", dest);   
        }   
    }   
   
    return 0;
}
Exemplo n.º 14
0
/* Thanks to John Bollinger <*****@*****.**> who has tested the
   windows part */
static char *
recursivefullname(const char *path, const char *filename, TBOOLEAN recursive)
{
    char *fullname = NULL;
    FILE *fp;

    /* length of path, dir separator, filename, \0 */
    fullname = gp_alloc(strlen(path) + 1 + strlen(filename) + 1,
			"recursivefullname");
    strcpy(fullname, path);
    PATH_CONCAT(fullname, filename);

    if ((fp = fopen(fullname, "r")) != NULL) {
	fclose(fp);
	return fullname;
    } else {
	free(fullname);
	fullname = NULL;
    }

    if (recursive) {
#ifdef HAVE_DIRENT_H
	DIR *dir;
	struct dirent *direntry;
	struct stat buf;

	dir = opendir(path);
	if (dir) {
	    while ((direntry = readdir(dir)) != NULL) {
		char *fulldir = gp_alloc(strlen(path) + 1 + strlen(direntry->d_name) + 1,
					 "fontpath_fullname");
		strcpy(fulldir, path);
#  if defined(VMS)
		if (fulldir[strlen(fulldir) - 1] == ']')
		    fulldir[strlen(fulldir) - 1] = '\0';
		strcpy(&(fulldir[strlen(fulldir)]), ".");
		strcpy(&(fulldir[strlen(fulldir)]), direntry->d_name);
		strcpy(&(fulldir[strlen(fulldir)]), "]");
#  else
		PATH_CONCAT(fulldir, direntry->d_name);
#  endif
		stat(fulldir, &buf);
		if ((S_ISDIR(buf.st_mode)) &&
		    (strcmp(direntry->d_name, ".") != 0) &&
		    (strcmp(direntry->d_name, "..") != 0)) {
		    fullname = recursivefullname(fulldir, filename, TRUE);
		    if (fullname != NULL)
			break;
		}
		free(fulldir);
	    }
	    closedir(dir);
	}
#elif defined(_Windows)
	HANDLE filehandle;
	WIN32_FIND_DATA finddata;
	char *pathwildcard = gp_alloc(strlen(path) + 2, "fontpath_fullname");

	strcpy(pathwildcard, path);
	PATH_CONCAT(pathwildcard, "*");

	filehandle = FindFirstFile(pathwildcard, &finddata);
	free(pathwildcard);
	if (filehandle != INVALID_HANDLE_VALUE)
	    do {
		if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
		    (strcmp(finddata.cFileName, ".") != 0) &&
		    (strcmp(finddata.cFileName, "..") != 0)) {
		    char *fulldir = gp_alloc(strlen(path) + 1 + strlen(finddata.cFileName) + 1,
					     "fontpath_fullname");
		    strcpy(fulldir, path);
		    PATH_CONCAT(fulldir, finddata.cFileName);

		    fullname = recursivefullname(fulldir, filename, TRUE);
		    free(fulldir);
		    if (fullname != NULL)
			break;
		}
	    } while (FindNextFile(filehandle, &finddata) != 0);
	FindClose(filehandle);

#else
	int_warn(NO_CARET, "Recursive directory search not supported\n\t('%s!')", path);
#endif
    }
    return fullname;
}
Exemplo n.º 15
0
/******************************************************************************
**
** Name: DI_list - Use WIN32 NT directory listing interface to list files
**
** Description:
**	List all files/directories in a given directory depending on
**	list_type argument.
**
** Inputs:
**      path                 Pointer to the path name.
**      pathlength           Length of path name.
**	    list_type	         type of object to list (DIRECTORY or FILE)
**	    func		         function to call for each object found.
**	    arg_list	         arguments to call the function with.
**
** Outputs:
**      err_code             Pointer to a variable used
**                           to return operating system
**                           errors.
**
**    Returns:
**        DI_BADDIR          Path specification error.
**        DI_ENDFILE         Error returned from client handler or
**                           all files listed.
**        DI_BADPARAM        Parameter(s) in error.
**        DI_DIRNOTFOUND     Path not found.
**        DI_BADLIST         Error trying to list objects.
**
**    Exceptions:
**        none
**
** Side Effects:
**        none
**
** History:
**	07-jul-1995 (canor01)
**	    convert filename returned from FindFirstFile() to lowercase, since
**	    other DI functions (via unix) expect lowercase.
**      18-jul-1995 (reijo01)
**          Changed SETWIN32ERR so that it will populate the CL_ERR_DESC with
**              the proper values.
**      08-dec-1997 (canor01)
**          Implement LRU for open files (initial copy from Unix).
**	28-jan-1998 (canor01)
**	    Correct a problem with previous implementation.  If closing
**	    files succeeds, retry, else bail out with error.
**	04-mar-1998 (canor01)
**	    Parameters to DIlru_flush were changed on Unix side.  Change
**	    them here too.
**
******************************************************************************/
static STATUS
DI_list(char       *path,
        u_i4       pathlength,
        i4         list_type,
        STATUS     (*func) (),
        PTR        arg_list,
        CL_SYS_ERR *err_code)
{
	STATUS          ret_val = OK;
	STATUS          dos_call;

	char            input_path[DI_PATH_MAX];
	HANDLE          handle;
	ULONG           count = 1;
	WIN32_FIND_DATA findbuf;

	/* default returns */

	CLEAR_ERR(err_code);

	/* Check input parameters */

	if ((pathlength > DI_PATH_MAX) ||
	    (pathlength == 0))
		return DI_BADPARAM;

	/* get null terminated path to the directory */

	memcpy(input_path, path, pathlength);
	memcpy(input_path + pathlength, "\\*.*", 5);

	/* break out on errors */

	while ( (handle = FindFirstFile(input_path, &findbuf)) == 
		INVALID_HANDLE_VALUE )
	{
		switch (dos_call = GetLastError()) 
		{
            	case ERROR_NO_SYSTEM_RESOURCES:
                case ERROR_TOO_MANY_OPEN_FILES:
                case ERROR_NO_MORE_FILES:
                case ERROR_NOT_ENOUGH_MEMORY:
                case ERROR_OUTOFMEMORY:
                case ERROR_HANDLE_DISK_FULL:
                case ERROR_OUT_OF_STRUCTURES:
                case ERROR_NONPAGED_SYSTEM_RESOURCES:
                case ERROR_PAGED_SYSTEM_RESOURCES:
            		if (DIlru_flush( err_code ) != OK)
            		{
                	    ret_val = DI_BADLIST;
            		}
			else
			{
			    continue;
			}
                	break;
		case ERROR_PATH_NOT_FOUND:
			SETWIN32ERR(err_code, dos_call, ER_list);
			ret_val = DI_DIRNOTFOUND;
			break;
		default:
			SETWIN32ERR(err_code, dos_call, ER_list);
			ret_val = DI_BADLIST;
			break;
		}
		if ( ret_val != OK )
		    return(ret_val);
	}

	/* now loop through all entries in the directory */

	ret_val = DI_ENDFILE;

	do {
		if (!memcmp(findbuf.cFileName, ".", 2) ||
		    !memcmp(findbuf.cFileName, "..", 3)) 
		{
			continue;
		}

		/*
		 * This next check is a leftover from OS/2.  Should dump it
		 * at some point, or enlarge the functionality of this
		 * routine. If we're looking for a directory, verify it is
		 * one...
		 */

		if (list_type == DIRECTORY) 
		{
			if (~findbuf.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
				continue;
			}
		}

		/* 
		* other functions expect lowercase name, but DOS
		* returns uppercase
                *
                * bug fix 89213.  
                * Unlike DOS, NT returns upper and lower case
                * names.
		*/
		if ((*func) (arg_list,
		             findbuf.cFileName,
		             STlength(findbuf.cFileName),
		             err_code)) 
		{
			ret_val = DI_ENDFILE;
			break;
		}
	} while (FindNextFile(handle, &findbuf));

	if (!FindClose(handle)) 	
	{
		SETWIN32ERR(err_code, GetLastError(), ER_list);
		ret_val = DI_BADLIST;
	}

	return (ret_val);
}
Exemplo n.º 16
0
bool TopMenuCore::startup()
{
   SetLastError(ERROR_SUCCESS);
   DWORD le;

   if(!m_hStopEvent) {
      note("could not create stop event");
      return false;
   }
   
   char szLibPath[MAX_PATH];
   if(!GetModuleFileName((HINSTANCE)&__ImageBase, szLibPath, MAX_PATH)) {
      le = GetLastError();
      return false;
   }

   char szLibDrive[MAX_PATH];
   char szLibDir[MAX_PATH];
   char szLibFname[MAX_PATH];
   char szLibExt[MAX_PATH];
   _splitpath_s(szLibPath, szLibDrive, szLibDir, szLibFname, szLibExt); //lint !e534 JLD
   _makepath_s(szLibPath, szLibDrive, szLibDir, "*", "dll"); //lint !e534 JLD
   
   WIN32_FIND_DATA findData;
   HANDLE hSearch = FindFirstFile(szLibPath, &findData);
   if(hSearch) {
      do 
      {
         char szPath[MAX_PATH];
         _makepath_s(szPath, szLibDrive, szLibDir, findData.cFileName, ""); //lint !e534 JLD

         HMODULE hPluginMod = LoadLibrary(szPath);
         if(!hPluginMod) {
            le = GetLastError();
            continue;
         }

         FARPROC createProc = GetProcAddress(hPluginMod, CREATE_PROC_NAME);
         if(!createProc) {
            le = GetLastError();
            FreeLibrary(hPluginMod); //lint !e534 JLD
            continue;
         }

         FARPROC versionProc = GetProcAddress(hPluginMod, VERSION_PROC_NAME);
         if(!versionProc) {
            le = GetLastError();
            FreeLibrary(hPluginMod); //lint !e534 JLD
            continue;
         }
         
         TopMenu_PluginStackEntry* pStackPtr = m_pTopEntry;
         while(pStackPtr) {
            if(pStackPtr->m_hModule == hPluginMod) {
               break; // module already in stack
            }
         }
         if(pStackPtr) {
            FreeLibrary(hPluginMod); //lint !e534 JLD
            continue; // plugin already loaded
         }
      
         VERSION_PROC& GetPluginVersion = (VERSION_PROC&)*versionProc;
         DWORD pluginVersion = GetPluginVersion();
         if(pluginVersion < TopMenu_Plugin::GetPluginVersion()) {
            le = GetLastError();
            FreeLibrary(hPluginMod); //lint !e534 JLD
            continue;
         }

         CREATE_PROC& CreatePlugin = (CREATE_PROC&)*createProc;
         TopMenu_Plugin* pPlugin = CreatePlugin();
         if(!pPlugin) {
            le = GetLastError();
            FreeLibrary(hPluginMod); //lint !e534 JLD
            continue;
         }

         TopMenu_PluginStackEntry* pPluginEntry = new TopMenu_PluginStackEntry();
         pPluginEntry->m_hModule = hPluginMod;
         pPluginEntry->m_pPlugin = pPlugin;
         if(m_pTopEntry) {
            pPluginEntry->m_pNext = m_pTopEntry;
         }
         m_pTopEntry = pPluginEntry;
      } while(FindNextFile(hSearch, &findData));

      FindClose(hSearch); //lint !e534 JLD
      hSearch = NULL;
   }

   return true;
} //lint !e550 JLD
Exemplo n.º 17
0
void
Win32AsyncFile::rmrfReq(Request * request, const char * src, bool removePath){
  if (!request->par.rmrf.directory)
  {
    // Remove file
    if (!DeleteFile(src))
    {
      DWORD dwError = GetLastError();
      if (dwError != ERROR_FILE_NOT_FOUND)
	request->error = dwError;
    }
    return;
  }

  char path[PATH_MAX];
  strcpy(path, src);
  strcat(path, "\\*");

  WIN32_FIND_DATA ffd;
  HANDLE hFindFile;
loop:
  hFindFile = FindFirstFile(path, &ffd);
  if (INVALID_HANDLE_VALUE == hFindFile)
  {
    DWORD dwError = GetLastError();
    if (dwError != ERROR_PATH_NOT_FOUND)
      request->error = dwError;
    return;
  }
  path[strlen(path) - 1] = 0; // remove '*'

  do {
    if (0 != strcmp(".", ffd.cFileName) && 0 != strcmp("..", ffd.cFileName))
    {
      int len = (int)strlen(path);
      strcat(path, ffd.cFileName);
      if(DeleteFile(path) || RemoveDirectory(path)) 
      {
        path[len] = 0;
	continue;
      }//if

      FindClose(hFindFile);
      strcat(path, "\\*");
      goto loop;
    }
  } while(FindNextFile(hFindFile, &ffd));
  
  FindClose(hFindFile);
  path[strlen(path)-1] = 0; // remove '\'
  if (strcmp(src, path) != 0)
  {
    char * t = strrchr(path, '\\');
    t[1] = '*';
    t[2] = 0;
    goto loop;
  }

  if(removePath && !RemoveDirectory(src))
    request->error = GetLastError();
}
Exemplo n.º 18
0
INT cmd_move (LPTSTR param)
{
    LPTSTR *arg;
    INT argc, i, nFiles;
    LPTSTR pszDest;
    TCHAR szDestPath[MAX_PATH];
    TCHAR szFullDestPath[MAX_PATH];
    TCHAR szSrcDirPath[MAX_PATH];
    TCHAR szSrcPath[MAX_PATH];
    TCHAR szFullSrcPath[MAX_PATH];
    DWORD dwFlags = 0;
    INT nOverwrite = 0;
    WIN32_FIND_DATA findBuffer;
    HANDLE hFile;

    /* used only when source and destination  directories are on different volume */
    HANDLE hDestFile = NULL;
    WIN32_FIND_DATA findDestBuffer;
    TCHAR szMoveDest[MAX_PATH];
    TCHAR szMoveSrc[MAX_PATH];
    LPTSTR pszDestDirPointer;
    LPTSTR pszSrcDirPointer;
    INT nDirLevel = 0;

    LPTSTR pszFile;
    BOOL OnlyOneFile;
    BOOL FoundFile;
    BOOL MoveStatus;
    DWORD dwMoveFlags = 0;
    DWORD dwMoveStatusFlags = 0;

    if (!_tcsncmp (param, _T("/?"), 2))
    {
#if 0
        ConOutPuts (_T("Moves files and renames files and directories.\n\n"
            "To move one or more files:\n"
            "MOVE [/N][/Y|/-Y][drive:][path]filename1[,...] destination\n"
            "\n"
            "To rename a directory:\n"
            "MOVE [/N][/Y|/-Y][drive:][path]dirname1 dirname2\n"
            "\n"
            "  [drive:][path]filename1  Specifies the location and name of the file\n"
            "                           or files you want to move.\n"
            "  /N                       Nothing. Don everthing but move files or directories.\n"
            "  /Y\n"
            "  /-Y\n"
            "..."));
#else
        ConOutResPaging(TRUE,STRING_MOVE_HELP2);
#endif
        return 0;
    }

    nErrorLevel = 0;
    arg = splitspace(param, &argc);

    /* read options */
    for (i = 0; i < argc; i++)
    {
        if (!_tcsicmp(arg[i], _T("/N")))
            dwFlags |= MOVE_NOTHING;
        else if (!_tcsicmp(arg[i], _T("/Y")))
            dwFlags |= MOVE_OVER_YES;
        else if (!_tcsicmp(arg[i], _T("/-Y")))
            dwFlags |= MOVE_OVER_NO;
        else
            break;
    }
    nFiles = argc - i;

    if (nFiles < 1)
    {
        /* there must be at least one pathspec */
        error_req_param_missing();
        freep(arg);
        return 1;
    }

    if (nFiles > 2)
    {
        /* there are more than two pathspecs */
        error_too_many_parameters(param);
        freep(arg);
        return 1;
    }

    /* If no destination is given, default to current directory */
    pszDest = (nFiles == 1) ? _T(".") : arg[i + 1];

    /* check for wildcards in source and destination */
    if (_tcschr(pszDest, _T('*')) != NULL || _tcschr(pszDest, _T('?')) != NULL)
    {
        /* '*'/'?' in dest, this doesnt happen.  give folder name instead*/
        error_invalid_parameter_format(pszDest);
        freep(arg);
        return 1;
    }
    if (_tcschr(arg[i], _T('*')) != NULL || _tcschr(arg[i], _T('?')) != NULL)
    {
        dwMoveStatusFlags |= MOVE_SOURCE_HAS_WILD;
    }

    /* get destination */
    GetFullPathName (pszDest, MAX_PATH, szDestPath, NULL);
    TRACE ("Destination: %s\n", debugstr_aw(szDestPath));

    /* get source folder */
    GetFullPathName(arg[i], MAX_PATH, szSrcDirPath, &pszFile);
    if (pszFile != NULL)
        *pszFile = _T('\0');
    TRACE ("Source Folder: %s\n", debugstr_aw(szSrcDirPath));

    hFile = FindFirstFile (arg[i], &findBuffer);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        ErrorMessage (GetLastError (), arg[i]);
        freep (arg);
        return 1;
    }

    /* check for special cases "." and ".." and if found skip them */
    FoundFile = TRUE;
    while(FoundFile &&
          (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
           _tcscmp(findBuffer.cFileName,_T("..")) == 0))
        FoundFile = FindNextFile (hFile, &findBuffer);

    if (!FoundFile)
    {
        /* what? we don't have anything to move? */
        error_file_not_found();
        FindClose(hFile);
        freep(arg);
        return 1;
    }

    OnlyOneFile = TRUE;
    /* check if there can be found files as files have first priority */
    if (findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        dwMoveStatusFlags |= MOVE_SOURCE_IS_DIR;
    else
        dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
    while(OnlyOneFile && FindNextFile(hFile,&findBuffer))
    {
        if (!(findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            ConOutPrintf(_T(""));
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) OnlyOneFile = FALSE;
            else
            {	/* this has been done this way so that we don't disturb other settings if they have been set before this */
                dwMoveStatusFlags |= MOVE_SOURCE_IS_FILE;
                dwMoveStatusFlags &= ~MOVE_SOURCE_IS_DIR;
            }
        }
    }
    FindClose(hFile);

    TRACE ("Do we have only one file: %s\n", OnlyOneFile ? "TRUE" : "FALSE");

    /* we have to start again to be sure we don't miss any files or folders*/
    hFile = FindFirstFile (arg[i], &findBuffer);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        ErrorMessage (GetLastError (), arg[i]);
        freep (arg);
        return 1;
    }

    /* check for special cases "." and ".." and if found skip them */
    FoundFile = TRUE;
    while(FoundFile &&
          (_tcscmp(findBuffer.cFileName,_T(".")) == 0 ||
           _tcscmp(findBuffer.cFileName,_T("..")) == 0))
        FoundFile = FindNextFile (hFile, &findBuffer);

    if (!FoundFile)
    {
        /* huh? somebody removed files and/or folders which were there */
        error_file_not_found();
        FindClose(hFile);
        freep(arg);
        return 1;
    }

    /* check if source and destination paths are on different volumes */
    if (szSrcDirPath[0] != szDestPath[0])
        dwMoveStatusFlags |= MOVE_PATHS_ON_DIF_VOL;

    /* move it */
    do
    {
        TRACE ("Found file/directory: %s\n", debugstr_aw(findBuffer.cFileName));
        nOverwrite = 1;
        dwMoveFlags = 0;
        dwMoveStatusFlags &= ~MOVE_DEST_IS_FILE &
                            ~MOVE_DEST_IS_DIR &
                            ~MOVE_SRC_CURRENT_IS_DIR &
                            ~MOVE_DEST_EXISTS;
        _tcscpy(szFullSrcPath,szSrcDirPath);
        if (szFullSrcPath[_tcslen(szFullSrcPath) -  1] != _T('\\'))
            _tcscat (szFullSrcPath, _T("\\"));
        _tcscat(szFullSrcPath,findBuffer.cFileName);
        _tcscpy(szSrcPath, szFullSrcPath);

        if (IsExistingDirectory(szSrcPath))
        {
            /* source is directory */
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE)
            {
                dwMoveStatusFlags |= MOVE_SRC_CURRENT_IS_DIR; /* source is file but at the current round we found a directory */
                continue;
            }
            TRACE ("Source is dir: %s\n", debugstr_aw(szSrcPath));
            dwMoveFlags = MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }

        /* if source is file we don't need to do anything special */
        if (IsExistingDirectory(szDestPath))
        {
            /* destination is existing directory */
            TRACE ("Destination is directory: %s\n", debugstr_aw(szDestPath));

            dwMoveStatusFlags |= MOVE_DEST_IS_DIR;

            /*build the dest string(accounts for *)*/
            _tcscpy (szFullDestPath, szDestPath);
            /*check to see if there is an ending slash, if not add one*/
            if (szFullDestPath[_tcslen(szFullDestPath) -  1] != _T('\\'))
                _tcscat (szFullDestPath, _T("\\"));
            _tcscat (szFullDestPath, findBuffer.cFileName);

            if (IsExistingFile(szFullDestPath) || IsExistingDirectory(szFullDestPath))
                dwMoveStatusFlags |= MOVE_DEST_EXISTS;

            dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }
        if (IsExistingFile(szDestPath))
        {
            /* destination is a file */
            TRACE ("Destination is file: %s\n", debugstr_aw(szDestPath));

            dwMoveStatusFlags |= MOVE_DEST_IS_FILE | MOVE_DEST_EXISTS;
            _tcscpy (szFullDestPath, szDestPath);

            dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }

        TRACE ("Move Status Flags: 0x%X\n",dwMoveStatusFlags);

        if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
            dwMoveStatusFlags & MOVE_DEST_IS_DIR &&
            dwMoveStatusFlags & MOVE_SOURCE_HAS_WILD)
        {
            /* We are not allowed to have existing source and destination dir when there is wildcard in source */
            error_syntax(NULL);
            FindClose(hFile);
            freep(arg);
            return 1;
        }
        if (!(dwMoveStatusFlags & (MOVE_DEST_IS_FILE | MOVE_DEST_IS_DIR)))
        {
            /* destination doesn't exist */
            _tcscpy (szFullDestPath, szDestPath);
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE) dwMoveStatusFlags |= MOVE_DEST_IS_FILE;
            if (dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) dwMoveStatusFlags |= MOVE_DEST_IS_DIR;

            dwMoveFlags |= MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED;
        }

        if (dwMoveStatusFlags & MOVE_SOURCE_IS_FILE &&
            dwMoveStatusFlags & MOVE_DEST_IS_FILE &&
            !OnlyOneFile)
        {
            /*source has many files but there is only one destination file*/
            error_invalid_parameter_format(pszDest);
            FindClose(hFile);
            freep (arg);
            return 1;
        }

        /*checks to make sure user wanted/wants the override*/
        if ((dwFlags & MOVE_OVER_NO) &&
           (dwMoveStatusFlags & MOVE_DEST_EXISTS))
            continue;
        if (!(dwFlags & MOVE_OVER_YES) &&
            (dwMoveStatusFlags & MOVE_DEST_EXISTS))
            nOverwrite = MoveOverwrite (szFullDestPath);
        if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
            continue;
        if (nOverwrite == PROMPT_ALL)
            dwFlags |= MOVE_OVER_YES;

        ConOutPrintf (_T("%s => %s "), szSrcPath, szFullDestPath);

        /* are we really supposed to do something */
        if (dwFlags & MOVE_NOTHING)
            continue;

        /*move the file*/
        if (!(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR &&
            dwMoveStatusFlags & MOVE_PATHS_ON_DIF_VOL))
            /* we aren't moving source folder to different drive */
            MoveStatus = MoveFileEx (szSrcPath, szFullDestPath, dwMoveFlags);
        else
        {	/* we are moving source folder to different drive */
            _tcscpy(szMoveDest, szFullDestPath);
            _tcscpy(szMoveSrc, szSrcPath);
            DeleteFile(szMoveDest);
            MoveStatus = CreateDirectory(szMoveDest, NULL); /* we use default security settings */
            if (MoveStatus)
            {
                _tcscat(szMoveDest,_T("\\"));
                _tcscat(szMoveSrc,_T("\\"));
                nDirLevel = 0;
                pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
                pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
                _tcscpy(pszSrcDirPointer,_T("*.*"));
                hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
                if (hDestFile == INVALID_HANDLE_VALUE)
                    MoveStatus = FALSE;
                else
                {
                    BOOL FirstTime = TRUE;
                    FoundFile = TRUE;
                    MoveStatus = FALSE;
                    while(FoundFile)
                    {
                        if (FirstTime)
                            FirstTime = FALSE;
                        else
                            FoundFile = FindNextFile (hDestFile, &findDestBuffer);

                        if (!FoundFile)
                        {
                            /* Nothing to do in this folder so we stop working on it */
                            FindClose(hDestFile);
                            (pszSrcDirPointer)--;
                            (pszDestDirPointer)--;
                            _tcscpy(pszSrcDirPointer,_T(""));
                            _tcscpy(pszDestDirPointer,_T(""));
                            if (nDirLevel > 0)
                            {
                                TCHAR szTempPath[MAX_PATH];
                                INT_PTR nDiff;

                                FoundFile = TRUE; /* we need to continue our seek for files */
                                nDirLevel--;
                                RemoveDirectory(szMoveSrc);
                                GetDirectory(szMoveSrc,szTempPath,0);
                                nDiff = _tcslen(szMoveSrc) - _tcslen(szTempPath);
                                pszSrcDirPointer = pszSrcDirPointer - nDiff;
                                _tcscpy(pszSrcDirPointer,_T(""));
                                GetDirectory(szMoveDest,szTempPath,0);
                                nDiff = _tcslen(szMoveDest) - _tcslen(szTempPath);
                                pszDestDirPointer = pszDestDirPointer - nDiff;
                                _tcscpy(pszDestDirPointer,_T(""));
                                if (szMoveSrc[_tcslen(szMoveSrc) -  1] != _T('\\'))
                                    _tcscat (szMoveSrc, _T("\\"));
                                if (szMoveDest[_tcslen(szMoveDest) -  1] != _T('\\'))
                                    _tcscat (szMoveDest, _T("\\"));
                                pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
                                pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
                                _tcscpy(pszSrcDirPointer,_T("*.*"));
                                hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
                                if (hDestFile == INVALID_HANDLE_VALUE)
                                    continue;
                                FirstTime = TRUE;
                            }
                            else
                            {
                                MoveStatus = TRUE; /* we moved everything so lets tell user about it */
                                RemoveDirectory(szMoveSrc);
                            }
                            continue;
                        }

                        /* if we find "." or ".." we'll skip them */
                        if (_tcscmp(findDestBuffer.cFileName,_T(".")) == 0 ||
                            _tcscmp(findDestBuffer.cFileName,_T("..")) == 0)
                            continue;

                        _tcscpy(pszSrcDirPointer, findDestBuffer.cFileName);
                        _tcscpy(pszDestDirPointer, findDestBuffer.cFileName);
                        if (IsExistingFile(szMoveSrc))
                        {
                            FoundFile = CopyFile(szMoveSrc, szMoveDest, FALSE);
                            if (!FoundFile) continue;
                            DeleteFile(szMoveSrc);
                        }
                        else
                        {
                            FindClose(hDestFile);
                            CreateDirectory(szMoveDest, NULL);
                            _tcscat(szMoveDest,_T("\\"));
                            _tcscat(szMoveSrc,_T("\\"));
                            nDirLevel++;
                            pszDestDirPointer = szMoveDest + _tcslen(szMoveDest);
                            pszSrcDirPointer = szMoveSrc + _tcslen(szMoveSrc);
                            _tcscpy(pszSrcDirPointer,_T("*.*"));
                            hDestFile = FindFirstFile(szMoveSrc, &findDestBuffer);
                            if (hDestFile == INVALID_HANDLE_VALUE)
                            {
                                FoundFile = FALSE;
                                continue;
                            }
                            FirstTime = TRUE;
                        }
                    }
                }
            }
        }
        if (MoveStatus)
            ConOutResPrintf(STRING_MOVE_ERROR1);
        else
            ConOutResPrintf(STRING_MOVE_ERROR2);
    }
    while ((!OnlyOneFile || dwMoveStatusFlags & MOVE_SRC_CURRENT_IS_DIR ) &&
            !(dwMoveStatusFlags & MOVE_SOURCE_IS_DIR) &&
            FindNextFile (hFile, &findBuffer));
    FindClose (hFile);

    if(hDestFile && hDestFile != INVALID_HANDLE_VALUE)
        FindClose(hDestFile);

    freep (arg);
    return 0;
}
Exemplo n.º 19
0
int
find_filenames_first(string_t fullpath_pro,string_t fullpath_des,string_t fullpath_par,
		     int *found_protocol,int *found_description, int *found_parameters)
{ 
  char *ptr;
#if HAVE_DIRENT_H
  DIR *dp;  
  struct dirent *np;
  
  dp = opendir(G.dirname);
  
  if (dp != NULL) {
    
    while ((np = readdir(dp)) != NULL) {
	  if (np->d_name != "." && np->d_name != "..") {

	    /* add *.protocol to "acquisition" protocol attribute */
	    ptr = strstr(np->d_name,"protocol");
	    if (ptr != NULL) {
	      *found_protocol = 1;
	      strcpy(fullpath_pro,np->d_name);
	    }
	   
	    /* add Description.txt to patient name and study id */
	    ptr = strstr(np->d_name,"Description.txt");
	    if (ptr != NULL) {
	      *found_description = 1;
	      strcpy(fullpath_des,np->d_name);
	    }
	    
	    /* add Parameters.txt to "acquisition" scan_parameters */
	    ptr = strstr(np->d_name,"Parameters.txt");
	    if (ptr != NULL) {
	      *found_parameters=1;
	      strcpy(fullpath_par,np->d_name);
	    }  
	  }
    }
 }
  closedir(dp);
#endif

#if defined (_MSC_VER)
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind = INVALID_HANDLE_VALUE;
  
  char DirSpec[MAX_BUF_LINE + 1];
  char dirname[MAX_BUF_LINE + 1];
  DWORD dwError;
  
  strncpy(DirSpec, G.dirname, MAX_BUF_LINE);
  DirSpec[MAX_BUF_LINE]='\0';
  strncat(DirSpec, "\\*", 3);
  /* make sure the directory ends with '/' */
  strncpy(dirname, G.dirname, MAX_BUF_LINE);
  dirname[MAX_BUF_LINE]='\0';
  if (G.dirname[strlen(G.dirname)-1] != '/') {
	strcat(dirname,"/");
  }

  hFind = FindFirstFile(DirSpec, &FindFileData);

  if (hFind == INVALID_HANDLE_VALUE) {
    printf(" Invalid file handle with Error %u \n", GetLastError());
    return(1);
  }
  else {
    
    do {
      /* add *.protocol to "acquisition" protocol attribute */
      ptr = strstr(FindFileData.cFileName,"protocol");
      if (ptr != NULL) {
	*found_protocol = 1;
	strcpy(fullpath_pro, dirname);
	strcat(fullpath_pro,FindFileData.cFileName);
      }

      /* add Description.txt to patient name and study id */
      ptr = strstr(FindFileData.cFileName,"Description.txt");
      if (ptr != NULL) {
	*found_description = 1;
	strcpy(fullpath_des, dirname);
	strcat(fullpath_des,FindFileData.cFileName);
      }
	    
      /* add Parameters.txt to "acquisition" scan_parameters */
      ptr = strstr(FindFileData.cFileName,"Parameters.txt");
      if (ptr != NULL) {
	*found_parameters=1;
	strcpy(fullpath_par, dirname);
	strcat(fullpath_par,FindFileData.cFileName);
      }  

    } while (FindNextFile(hFind, &FindFileData) != 0);

    dwError = GetLastError();
    FindClose(hFind);
    if (dwError != ERROR_NO_MORE_FILES) {
      printf(" Find next file %u\n", dwError);
      return(1);
    }
  }
#endif

  return(0);
}
Exemplo n.º 20
0
/*
** Entry point
**
*/
int SkinInstallerMain(LPWSTR lpCmdLine)
{
	// Avoid loading a dll from current directory
	SetDllDirectory(L"");

	CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
	InitCommonControls();

	if (lpCmdLine[0] == L'"')
	{
		// Strip quotes
		++lpCmdLine;
		WCHAR* pos = wcsrchr(lpCmdLine, L'"');
		if (pos)
		{
			*pos = L'\0';
		}
	}

	WCHAR buffer[MAX_PATH];
	GetModuleFileName(GetInstanceHandle(), buffer, MAX_PATH);

	// Remove the module's name from the path
	WCHAR* pos = wcsrchr(buffer, L'\\');
	if (pos)
	{
		*(pos + 1) = L'\0';
	}

	g_Data.programPath = g_Data.settingsPath = buffer;
	wcscat(buffer, L"Rainmeter.ini");

	// Find the settings file and read skins path off it
	if (_waccess(buffer, 0) == 0)
	{
		g_Data.iniFile = buffer;
		if (GetPrivateProfileString(L"Rainmeter", L"SkinPath", L"", buffer, MAX_LINE_LENGTH, buffer) > 0)
		{
			g_Data.skinsPath = buffer;
			if (g_Data.skinsPath.back() != L'\\' && g_Data.skinsPath.back() != L'/')
			{
				g_Data.skinsPath += L'\\';
			}
		}
		else
		{
			g_Data.skinsPath = g_Data.programPath;
			g_Data.skinsPath += L"Skins\\";
		}
	}
	else
	{
		HRESULT hr = SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, buffer);
		wcscat(buffer, L"\\Rainmeter\\");
		g_Data.settingsPath = buffer;
		wcscat(buffer, L"Rainmeter.ini");
		g_Data.iniFile = buffer;
		if (SUCCEEDED(hr) && _waccess(buffer, 0) == 0)
		{
			if (GetPrivateProfileString(L"Rainmeter", L"SkinPath", L"", buffer, MAX_LINE_LENGTH, buffer) > 0)
			{
				g_Data.skinsPath = buffer;
				if (g_Data.skinsPath.back() != L'\\' && g_Data.skinsPath.back() != L'/')
				{
					g_Data.skinsPath += L'\\';
				}
			}
			else
			{
				std::wstring error = L"SkinPath not found.\nMake sure that Rainmeter has been run at least once.";
				MessageBox(nullptr, error.c_str(), L"Rainmeter Skin Installer", MB_ERROR);
				return 1;
			}
		}
		else
		{
			std::wstring error = L"Rainmeter.ini not found.\nMake sure that Rainmeter has been run at least once.";
			MessageBox(nullptr, error.c_str(), L"Rainmeter Skin Installer", MB_ERROR);
			return 1;
		}
	}

	std::wstring layoutsPath = g_Data.settingsPath + L"Layouts\\";
	if (_waccess(layoutsPath.c_str(), 0) == -1)
	{
		// Migrate Themes into Layouts for backwards compatibility and rename
		// Rainmeter.thm to Rainmeter.ini and RainThemes.bmp to Wallpaper.bmp.
		std::wstring themesPath = g_Data.settingsPath + L"Themes";
		if (_waccess(themesPath.c_str(), 0) != -1)
		{
			// Migrate Themes into Layouts for backwards compatibility and rename
			// Rainmeter.thm to Rainmeter.ini and RainThemes.bmp to Wallpaper.bmp.
			MoveFile(themesPath.c_str(), layoutsPath.c_str());

			layoutsPath += L'*';  // For FindFirstFile.
			WIN32_FIND_DATA fd;
			HANDLE hFind = FindFirstFile(layoutsPath.c_str(), &fd);
			layoutsPath.pop_back();  // Remove '*'.

			if (hFind != INVALID_HANDLE_VALUE)
			{
				do
				{
					if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
						wcscmp(L".", fd.cFileName) != 0 &&
						wcscmp(L"..", fd.cFileName) != 0)
					{
						std::wstring layoutFolder = layoutsPath + fd.cFileName;
						layoutFolder += L'\\';

						std::wstring file = layoutFolder + L"Rainmeter.thm";
						if (_waccess(file.c_str(), 0) != -1)
						{
							std::wstring newFile = layoutFolder + L"Rainmeter.ini";
							MoveFile(file.c_str(), newFile.c_str());
						}

						file = layoutFolder + L"RainThemes.bmp";
						if (_waccess(file.c_str(), 0) != -1)
						{
							std::wstring newFile = layoutFolder + L"Wallpaper.bmp";
							MoveFile(file.c_str(), newFile.c_str());
						}
					}
				}
				while (FindNextFile(hFind, &fd));

				FindClose(hFind);
			}
		}
	}

	if (_wcsnicmp(lpCmdLine, L"/LoadTheme ", 11) == 0)
	{
		// For backwards compatibility.
		std::wstring args = L"!LoadLayout \"";
		args += &lpCmdLine[11];  // Skip "/LoadTheme ".
		args += L'"';

		std::wstring file = g_Data.programPath + L"Rainmeter.exe";
		SHELLEXECUTEINFO sei = {0};
		sei.cbSize = sizeof(SHELLEXECUTEINFO);
		sei.fMask = SEE_MASK_UNICODE;
		sei.lpFile = file.c_str();
		sei.lpParameters = args.c_str();
		sei.lpDirectory = g_Data.programPath.c_str();
		sei.nShow = SW_SHOWNORMAL;
		ShellExecuteEx(&sei);

		return 0;
	}
	else if (wcscmp(lpCmdLine, L"/Packager") == 0)
	{
		DialogPackage::Create(GetInstanceHandle(), lpCmdLine);
	}
	else
	{
		DialogInstall::Create(GetInstanceHandle(), lpCmdLine);
	}

	return 0;
}
Exemplo n.º 21
0
Collection* FileSystem::getFolderContent(Path* folder) {

	WIN32_FIND_DATA findFileData;
	HANDLE hFind = INVALID_HANDLE_VALUE;
	WCHAR dirSpec[MAX_PATH_LENGTH];
	DWORD dwError;
	Collection* result = new Collection();

	// prepare the folder name and append "\*"
	folder->copyName(cleanString(dirSpec));
	wcscat(dirSpec, L"\\*");

	hFind = FindFirstFile(dirSpec, &findFileData);

	if (hFind == INVALID_HANDLE_VALUE) {
		// Accessing "<drive>:\System Volume Information\*" gives an
		// ERROR_ACCESS_DENIED. So this has to be fixed to scan whole
		// volumes! Also can happen on folders with no access permissions.
		logError(GetLastError(), L"Unable to read folder content.");
	} else {
		do {
			// check if this is a valid file and not a dummy like "." or ".."
			if (wcscmp(findFileData.cFileName, L".") != 0 &&  wcscmp(findFileData.cFileName, L"..") != 0) {

				// check if we have found a file
				if (!(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
					Statistics::getInstance()->filesFound++;

					// check for hidden file
					if (!hiddenFiles && (findFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) {

						logDebug(L"ignoring hidden file \"%s\"", findFileData.cFileName);

					// check for system file
					} else if (!systemFiles && (findFileData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)) {

						logDebug(L"ignoring system file \"%s\"", findFileData.cFileName);

					} else {

						// add the path to the collection
						logFile(findFileData);

						File* item = new File(findFileData, folder);
						result->append(item);
					}
				} else {
					// Okay we found a directory!
					Statistics::getInstance()->directoriesFound++;

					// check for junction
					if (!followJunctions && (findFileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {

						logDebug(L"ignoring junction \"%s\"", findFileData.cFileName);

					} else {

						// add the path to the collection
						logFile(findFileData);
						result->append(new Path(findFileData.cFileName, folder));
					}
				}
			}
		} while (FindNextFile(hFind, &findFileData) != 0);

		dwError = GetLastError();
		FindClose(hFind);
		if (dwError != ERROR_NO_MORE_FILES) {
			LPWSTR buffer = new WCHAR[MAX_PATH_LENGTH];
			wsprintf(buffer, L"FindNextFile error. Error is %u\n", dwError);
			// clean up memory
			delete result;
			throw buffer;
		}
	}

	return result;
}
Exemplo n.º 22
0
	int FileList::enumerate(const char* directory, const char* extension) {
		std::string dir;
		std::string fname;
		std::string ext;
		unsigned int len;
		int num = 0;

#ifdef WIN32
		HANDLE hFind;
		WIN32_FIND_DATA fd;
#else
		DIR *pdir;
		struct dirent *pent;
#endif

		// ディレクトリ
		dir = directory;
		len = dir.length();

		// 拡張子
		ext = '.';
		ext += extension;

		// スラッシュを除去
		if( dir[len-1] == '/'
#ifdef WIN32
			|| dir[len-1] == '\\'
#endif
				) {
			dir = dir.substr(0, len-1);
		}

#ifdef WIN32
		// 拡張子に当てはまるファイルを列挙
		fname = dir + "\\*";
		if (1 < ext.length()) {
			fname += extension;
		}

		hFind = FindFirstFile(fname.c_str(), &fd);

		if( hFind == INVALID_HANDLE_VALUE ){
			Log::warning << "There are no files!..[" << fname << ']' << '\n';
			return 0;
		}
		dir += '\\';
#else
		// ディレクトリのオープン
		if ((pdir = opendir(dir.c_str())) == NULL) {
			Log::error << "Couldn't open the directory!..[" << dir << ']' << '\n';
			return 0;
		}
		dir += '/';
#endif

		for ( ; ; ) {
#ifdef WIN32
			fname = fd.cFileName;
#else
			if (NULL == (pent = readdir(pdir))) {
				closedir( pdir );
				break;
			}

			fname = pent->d_name;
#endif

			// ディレクトリ".", ".."の場合
			if (fname[fname.length()-1] == '.') {
				continue;
			}

#ifndef WIN32
			// 拡張子のチェック
			if (1 < (len = ext.length()) && (fname.length() <= len ||
					0 != strcasecmp(fname.substr(fname.length() - len).c_str(), ext.c_str()))) {
				continue;
			}
#endif

			// リストに追加
			flist.push_back(dir + fname);
			num++;

#ifdef WIN32
			// 次のファイル
			if (!FindNextFile( hFind, &fd)) {
				// ハンドルのクローズ
				FindClose( hFind );
				break;
			}
#endif
		}

		it = flist.begin();

		return num;
	}
Exemplo n.º 23
0
	/// Set the move char code for all characters in the account
	void Rename::AdminCmd_SetAccMoveCode(CCmds* cmds, const wstring &wscCharname, const wstring &wscCode)
	{
		// Don't indicate an error if moving is disabled.
		if (!set_bEnableMoveChar)
			return;

		if (!(cmds->rights & RIGHT_SUPERADMIN))
		{
			cmds->Print(L"ERR No permission\n");
			return;
		}

		wstring wscDir;
		if (HkGetAccountDirName(wscCharname, wscDir)!=HKE_OK)
		{
			cmds->Print(L"ERR Charname not found\n");
			return;
		}

		if (wscCode.length()==0)
		{
			cmds->Print(L"ERR Code too small, set to none to clear.\n");
			return;
		}

		// Get the account path.
		char szDataPath[MAX_PATH];
		GetUserDataPath(szDataPath);
		string scPath = string(szDataPath) + "\\Accts\\MultiPlayer\\" + wstos(wscDir) + "\\*.fl";

		// Open the directory iterator.
		WIN32_FIND_DATA FindFileData; 
		HANDLE hFileFind = FindFirstFile(scPath.c_str(), &FindFileData);
		if (hFileFind==INVALID_HANDLE_VALUE)
		{
			cmds->Print(L"ERR Account directory not found\n");
			return;
		}

		// Iterate it
		do
		{
			string scCharfile = FindFileData.cFileName;
			string scMoveCodeFile = string(szDataPath) + "\\Accts\\MultiPlayer\\" + wstos(wscDir) + "\\"
				+ scCharfile.substr(0,scCharfile.size()-3) + "-movechar.ini";
			if (wscCode==L"none")
			{
				IniWriteW(scMoveCodeFile, "Settings", "Code", L"");
				cmds->Print(L"OK Movechar code cleared on "+stows(scCharfile)+L"\n");
			}
			else
			{
				IniWriteW(scMoveCodeFile, "Settings", "Code", wscCode);
				cmds->Print(L"OK Movechar code set to "+wscCode +L" on "+stows(scCharfile)+L"\n");
			}
		}
		while (FindNextFile(hFileFind, &FindFileData));
		FindClose(hFileFind); 

		cmds->Print(L"OK\n");
	}
Exemplo n.º 24
0
HANDLE FindFirstFile(LPCSTR szPath,LPWIN32_FIND_DATA lpFindData)
{
  if (lpFindData == NULL || szPath == NULL)
    return NULL;

  CStdString strPath(szPath);

  if (IsAliasShortcut(strPath))
    TranslateAliasShortcut(strPath);

  if (strPath.empty())
    return INVALID_HANDLE_VALUE;

  strPath.Replace("\\","/");

  // if the file name is a directory then we add a * to look for all files in this directory
#if defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) || defined(TARGET_ANDROID)
  DIR *testDir = opendir(strPath.c_str());
#else
  DIR *testDir = opendir(szPath);
#endif
  if (testDir)
  {
    strPath += "/*";
    closedir(testDir);
  }

  int nFilePos = strPath.ReverseFind(XBMC_FILE_SEP);

  CStdString strDir = ".";
  CStdString strFiles = strPath;

  if (nFilePos > 0)
  {
    strDir = strPath.substr(0,nFilePos);
    strFiles = strPath.substr(nFilePos + 1);
  }

  if (strFiles == "*.*")
     strFiles = "*";

  strFiles = CStdString("^") + strFiles + "$";
  strFiles.Replace(".","\\.");
  strFiles.Replace("*",".*");
  strFiles.Replace("?",".");

  strFiles.MakeLower();  // Do we really want this case insensitive?
  CRegExp re(true);

  if (re.RegComp(strFiles.c_str()) == NULL)
    return(INVALID_HANDLE_VALUE);

  struct dirent **namelist = NULL;
#if defined(TARGET_ANDROID)
  // android is more strict with the sort function. Let's hope it is implemented correctly.
  typedef int (*sortFunc)(const struct dirent ** a, const struct dirent **b);
  int n = scandir(strDir, &namelist, 0, (sortFunc)alphasort);
#else
  int n = scandir(strDir, &namelist, 0, alphasort);
#endif

  CXHandle *pHandle = new CXHandle(CXHandle::HND_FIND_FILE);
    pHandle->m_FindFileDir = strDir;

  while (n-- > 0)
  {
    CStdString strComp(namelist[n]->d_name);
    strComp.MakeLower();

    if (re.RegFind(strComp.c_str()) >= 0)
      pHandle->m_FindFileResults.push_back(namelist[n]->d_name);
    free(namelist[n]);
  }
  free(namelist);

  if (pHandle->m_FindFileResults.size() == 0)
  {
    delete pHandle;
    return INVALID_HANDLE_VALUE;
  }

  FindNextFile(pHandle, lpFindData);

  return pHandle;
}
Exemplo n.º 25
0
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
   LPWIN32_FIND_DATAW ffd;
   LARGE_INTEGER filesize;
   WCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;
   LPWSTR *szArgList;
   int argCount;

   std::ofstream logFile;
   logFile.open ("FileListing.log");

   
   // If the directory is not specified as a command-line argument,
   // print usage.

  szArgList = CommandLineToArgvW((LPCWSTR)GetCommandLine(), &argCount);

  if(argCount !=2)
	  logFile << "\nUsage: %s <directory name>\n" << szArgList[0];

   /*if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }*/

   // Check that the input path plus 3 is not longer than MAX_PATH.
   // Three characters are for the "\*" plus NULL appended below.

   StringCchLengthW(szArgList[1], MAX_PATH,  (size_t *)&argCount);

   if ( argCount > (MAX_PATH - 3))
   {
      logFile << "\nDirectory path is too long.\n";
      return (-1);
   }

  logFile <<"\nTarget directory is "<<szArgList[1] <<":\n\n";

   // Prepare string for use with FindFile functions. First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopyW(szDir, MAX_PATH, szArgList[1]);
   StringCchCatW(szDir, MAX_PATH, L"\\*");

   // Find the first file in the directory.

   hFind = FindFirstFileW(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
      return dwError;
   } 
   
   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);
 
   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      DisplayErrorBox(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;

	return 0;
}
Exemplo n.º 26
0
Arquivo: tree.c Projeto: RPG-7/reactos
/**
 * @name: GetDirectoryStructure
 * 
 * @param strPath
 * Must specify folder name
 *
 * @param width
 * specifies drawing distance for correct formatting of tree structure being drawn on console screen
 *
 * @param prevLine
 * specifies the previous line written on console, is used for correct formatting
 * @return
 * void
 */
static void
GetDirectoryStructure(wchar_t* strPath, UINT width, const wchar_t* prevLine)
{
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = NULL;
    //DWORD err = 0;
    /* will fill up with names of all sub folders */
    WIN32_FIND_DATA *arrFolder = NULL;
    UINT arrFoldersz = 0;
    /* will fill up with names of all sub folders */
    WIN32_FIND_DATA *arrFile = NULL;
    UINT arrFilesz = 0;

    ZeroMemory(&FindFileData, sizeof(FindFileData));

    {
        static wchar_t tmp[STR_MAX] = L"";
        ZeroMemory(tmp, sizeof(tmp));
        wcscat(tmp, strPath);
        wcscat(tmp, L"\\*.*");
        hFind = FindFirstFile(tmp, &FindFileData);
        //err = GetLastError(); 
    }

    if (hFind == INVALID_HANDLE_VALUE)
        return;

    do
    {
        if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            if (wcscmp(FindFileData.cFileName, L".") == 0 ||
                wcscmp(FindFileData.cFileName, L"..") == 0)
                continue;

            ++arrFoldersz;
            arrFolder = (WIN32_FIND_DATA*)realloc(arrFolder, arrFoldersz * sizeof(FindFileData));

            if (arrFolder == NULL)
                exit(-1);

            arrFolder[arrFoldersz - 1] = FindFileData;

        }
        else
        {
            ++arrFilesz;
            arrFile = (WIN32_FIND_DATA*)realloc(arrFile, arrFilesz * sizeof(FindFileData));

            if(arrFile == NULL)
                exit(-1);

            arrFile[arrFilesz - 1] = FindFileData;
        }
    }
    while (FindNextFile(hFind, &FindFileData));

    FindClose(hFind);

    if (bShowFiles)
    {
        /* will free(arrFile) */
        DrawTree(strPath, arrFile, arrFilesz, width, prevLine, FALSE);
    }

    /* will free(arrFile) */
    DrawTree(strPath, arrFolder, arrFoldersz, width, prevLine, TRUE);

    free(arrFolder);
    free(arrFile);
}
Exemplo n.º 27
0
VOID CloseXMLRootElement(_In_ PTCHAR tPath)
{
	HANDLE hXMLFile = INVALID_HANDLE_VALUE;
	HANDLE hNode = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA sFindDataMask;
	TCHAR tFindPath[MAX_PATH];
	TCHAR tFullNamePath[MAX_PATH];
	DWORD dwDataRead = 0;
	LARGE_INTEGER liDistanceToMove;

	// Fixing path by adding /* at the end for matching with regexp engine
	if ((StringCchCopy(tFindPath, MAX_PATH, tPath) != S_OK)
		|| (StringCchCat(tFindPath, MAX_PATH, TEXT("\\*")) != S_OK))
	{
		DEBUG_LOG(D_WARNING, "Unable to compute output path folder.\r\nExiting now...");
		DoExit(D_ERROR);
	}

	hNode = FindFirstFile(tFindPath, &sFindDataMask);
	if (hNode == INVALID_HANDLE_VALUE)
	{
		DEBUG_LOG(D_ERROR, "Unable to close XML file %ws.\r\nExiting now...", tFindPath);
			DoExit(1);
	}

	// Following file type we dispacth it
	do
	{
		if (sFindDataMask.cFileName == NULL)
		{
			DEBUG_LOG(D_WARNING, "Folder node with no name found !\r\n");
			continue;
		}
		else if (!_tcscmp(sFindDataMask.cFileName, TEXT(".")) 
			|| !_tcscmp(sFindDataMask.cFileName, TEXT("..")))
			continue;

		// build targeted folder full path
		StringCchCopy(tFullNamePath, MAX_PATH, tPath);
		StringCchCat(tFullNamePath, MAX_PATH, TEXT("\\"));
		StringCchCat(tFullNamePath, MAX_PATH, sFindDataMask.cFileName);

		if (sFindDataMask.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			CloseXMLRootElement(tFullNamePath);

		// Close XML file
		if (_tcsstr(sFindDataMask.cFileName, TEXT(".xml")))
		{
			hXMLFile = CreateFile_s(tFullNamePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hXMLFile == INVALID_HANDLE_VALUE)
			{
				DEBUG_LOG(D_WARNING, "Unable to close xml file for format: %ws (err=%d).\r\nExiting now...", tFullNamePath, GetLastError());
				DoExit(D_ERROR);
			}

			ZeroMemory(&liDistanceToMove, sizeof(LARGE_INTEGER));
			if (SetFilePointerEx(hXMLFile, liDistanceToMove, NULL, FILE_END) == INVALID_SET_FILE_POINTER)
			{
				DEBUG_LOG(D_WARNING, "Unable to move file pointer to the end of the file for: %ws.\r\nExiting now...", tFullNamePath);
				DoExit(D_ERROR);
			}

			if ((WriteFile(hXMLFile, TEXT("</"), (DWORD)(_tcslen(TEXT("</")) * sizeof (TCHAR)), &dwDataRead, NULL) == FALSE)
			|| (WriteFile(hXMLFile, sFindDataMask.cFileName, (DWORD)(_tcslen(sFindDataMask.cFileName) * sizeof (TCHAR)), &dwDataRead, NULL) == FALSE)
			|| (WriteFile(hXMLFile, TEXT(">\r\n"), (DWORD)(_tcslen(TEXT(">\r\n")) * sizeof (TCHAR)), &dwDataRead, NULL) == FALSE))
			{
				DEBUG_LOG(D_WARNING, "Unable add XML root element for file %ws.\r\nExiting now...", tFullNamePath);
				DoExit(D_ERROR);
			}

			CloseHandle(hXMLFile);
		}

	}
	while (FindNextFile(hNode, &sFindDataMask) != 0);
	FindClose(hNode);
}
Exemplo n.º 28
0
void DayLog_ReadAccountInDir(char *dir, FILE *log)
{
	HANDLE handle;
	WIN32_FIND_DATA win32_find_data;

	char tmp[1024];
	char tmp2[1024];

	handle = FindFirstFile(dir, &win32_find_data);

	if (handle == INVALID_HANDLE_VALUE)
	{
		// TODO: Error: can't read initial file
	}
	else
	{
		while (FindNextFile(handle, &win32_find_data))
		{
			char *fileName = win32_find_data.cFileName;

			if (!strncmp(fileName, ".", 1))
				continue;

			if (win32_find_data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
			{
				sprintf(tmp, "./account/%s/*", fileName);
				DayLog_ReadAccountInDir(tmp, log);
			}
			else
			{
				SYSTEMTIME fWriteTime;
				SYSTEMTIME sysTime;
				FileTimeToSystemTime(&win32_find_data.ftLastWriteTime, &fWriteTime);
				GetLocalTime(&sysTime);

				// Only use fresh active accounts 
				if (fWriteTime.wYear != sysTime.wYear || fWriteTime.wMonth != sysTime.wMonth)
					continue;

				strcpy(tmp, dir);
				tmp[strlen(dir) - 1] = '\0';
				sprintf(tmp, "%s%s", tmp, fileName);

				errno = 0;
				FILE* fs;
				fopen_s(&fs, tmp, "rb");

				if (fs != NULL)
				{
					STRUCT_ACCOUNTFILE accBuffer;
					memset(&accBuffer, 0, sizeof(STRUCT_ACCOUNTFILE));

					fread(&accBuffer, sizeof(STRUCT_ACCOUNTFILE), 1, fs);

					struct tm when;
					time_t now;
					time(&now);
					when = *localtime(&now);

					for (int i = 0; i < MOB_PER_ACCOUNT; i++)
					{
						if (accBuffer.Char[i].MobName[0] == '\0')
							continue;

						if (accBuffer.mobExtra[i].DayLog.YearDay == when.tm_yday-1)
							fprintf(log, "[%02d/%02d/%04d][%02d:%02d:%02d] %s Char:%s recebeu %llu exp hoje.\n", when.tm_mday, when.tm_mon + 1, when.tm_year + 1900, when.tm_hour, when.tm_min, when.tm_sec, accBuffer.Info.AccountName, accBuffer.Char[i].MobName, accBuffer.mobExtra[i].DayLog.Exp);
						
					}

					fclose(fs);
				}
				else
				{
					// TODO: Cant open file to read
				}
			}
		}
	}

	FindClose(handle);
}
Exemplo n.º 29
0
int32_t dt_control_delete_images_job_run(dt_job_t *job)
{
  int imgid = -1;
  dt_control_image_enumerator_t *t1 = (dt_control_image_enumerator_t *)job->param;
  GList *t = t1->index;
  char *imgs = _get_image_list(t);
  int total = g_list_length(t);
  char message[512]= {0};
  double fraction=0;
  snprintf(message, 512, ngettext ("deleting %d image", "deleting %d images", total), total );
  const guint *jid = dt_control_backgroundjobs_create(darktable.control, 0, message);

  sqlite3_stmt *stmt;

  _set_remove_flag(imgs);

  dt_collection_update(darktable.collection);

  // We need a list of files to regenerate .xmp files if there are duplicates
  GList *list = _get_full_pathname(imgs);

  free(imgs);

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select count(id) from images where filename in (select filename from images where id = ?1) and film_id in (select film_id from images where id = ?1)", -1, &stmt, NULL);
  while(t)
  {
    imgid = GPOINTER_TO_INT(t->data);
    char filename[DT_MAX_PATH_LEN];
    gboolean from_cache = FALSE;
    dt_image_full_path(imgid, filename, DT_MAX_PATH_LEN, &from_cache);

    int duplicates = 0;
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgid);
    if(sqlite3_step(stmt) == SQLITE_ROW)
      duplicates = sqlite3_column_int(stmt, 0);
    sqlite3_reset(stmt);
    sqlite3_clear_bindings(stmt);

    // remove from disk:
    if(duplicates == 1)
    {
      // there are no further duplicates so we can remove the source data file
      (void)g_unlink(filename);
      dt_image_remove(imgid);

      // all sidecar files - including left-overs - can be deleted;
      // left-overs can result when previously duplicates have been REMOVED;
      // no need to keep them as the source data file is gone.
      const int len = DT_MAX_PATH_LEN + 30;
      gchar pattern[len];

      // NULL terminated list of glob patterns; should include "" and can be extended if needed
      static const gchar *glob_patterns[] = { "", "_[0-9][0-9]", "_[0-9][0-9][0-9]", "_[0-9][0-9][0-9][0-9]", NULL };

      const gchar **glob_pattern = glob_patterns;
      GList *files = NULL;
      while(*glob_pattern)
      {
        snprintf(pattern, len, "%s", filename);
        gchar *c1 = pattern + strlen(pattern);
        while(*c1 != '.' && c1 > pattern) c1--;
        snprintf(c1, pattern + len - c1, "%s", *glob_pattern);
        const gchar *c2 = filename + strlen(filename);
        while(*c2 != '.' && c2 > filename) c2--;
        snprintf(c1+strlen(*glob_pattern), pattern + len - c1 - strlen(*glob_pattern), "%s.xmp", c2);

#ifdef __WIN32__
        WIN32_FIND_DATA data;
        HANDLE handle = FindFirstFile(pattern, &data);
        if(handle != INVALID_HANDLE_VALUE)
        {
          do
            files = g_list_append(files, g_strdup(data.cFileName));
          while(FindNextFile(handle, &data));
        }
#else
        glob_t globbuf;
        if(!glob(pattern, 0, NULL, &globbuf))
        {
          for(size_t i=0; i < globbuf.gl_pathc; i++)
            files = g_list_append(files, g_strdup(globbuf.gl_pathv[i]));
          globfree(&globbuf);
        }
#endif

        glob_pattern++;
      }

      GList *file_iter = g_list_first(files);
      while(file_iter != NULL)
      {
        (void)g_unlink(file_iter->data);
        file_iter = g_list_next(file_iter);
      }

      g_list_free_full(files, g_free);
    }
    else
    {
      // don't remove the actual source data if there are further duplicates using it;
      // just delete the xmp file of the duplicate selected.

      dt_image_path_append_version(imgid, filename, DT_MAX_PATH_LEN);
      char *c = filename + strlen(filename);
      sprintf(c, ".xmp");

      dt_image_remove(imgid);
      (void)g_unlink(filename);
    }

    t = g_list_delete_link(t, t);
    fraction=1.0/total;
    dt_control_backgroundjobs_progress(darktable.control, jid, fraction);
  }
  sqlite3_finalize(stmt);

  char *imgname;
  while(list)
  {
    imgname = (char *)list->data;
    dt_image_synch_all_xmp(imgname);
    list = g_list_delete_link(list, list);
  }
  g_list_free(list);
  dt_control_backgroundjobs_destroy(darktable.control, jid);
  dt_film_remove_empty();
  dt_control_signal_raise(darktable.signals, DT_SIGNAL_FILMROLLS_CHANGED);
  dt_control_queue_redraw_center();
  return 0;
}
Exemplo n.º 30
0
ArrayT<const SoundShaderT*> SoundShaderManagerImplT::RegisterSoundShaderScriptsInDir(const std::string& Directory, const std::string& ModDir, bool Recurse)
{
    ArrayT<const SoundShaderT*> NewSoundShaders;

    if (Directory=="") return NewSoundShaders;

#ifdef _MSC_VER
    WIN32_FIND_DATA FindFileData;

    HANDLE hFind=FindFirstFile((Directory+"\\*").c_str(), &FindFileData);

    // MessageBox(NULL, hFind==INVALID_HANDLE_VALUE ? "INV_VALUE!!" : FindFileData.cFileName, "Starting parsing.", MB_ICONINFORMATION);
    if (hFind==INVALID_HANDLE_VALUE) return NewSoundShaders;

    ArrayT<std::string> DirEntNames;

    do
    {
        // MessageBox(NULL, FindFileData.cFileName, "Material Script Found", MB_ICONINFORMATION);
        if (!_stricmp(FindFileData.cFileName, "."  )) continue;
        if (!_stricmp(FindFileData.cFileName, ".." )) continue;
        if (!_stricmp(FindFileData.cFileName, "cvs")) continue;

        DirEntNames.PushBack(Directory+"/"+FindFileData.cFileName);
    } while (FindNextFile(hFind, &FindFileData)!=0);

    if (GetLastError()==ERROR_NO_MORE_FILES) FindClose(hFind);
#else
    DIR* Dir=opendir(Directory.c_str());

    if (!Dir) return NewSoundShaders;

    ArrayT<std::string> DirEntNames;

    for (dirent* DirEnt=readdir(Dir); DirEnt!=NULL; DirEnt=readdir(Dir))
    {
        if (!strcasecmp(DirEnt->d_name, "."  )) continue;
        if (!strcasecmp(DirEnt->d_name, ".." )) continue;
        if (!strcasecmp(DirEnt->d_name, "cvs")) continue;

        // For portability, only the 'd_name' member of a 'dirent' may be accessed.
        DirEntNames.PushBack(Directory+"/"+DirEnt->d_name);
    }

    closedir(Dir);
#endif


    for (unsigned long DENr=0; DENr<DirEntNames.Size(); DENr++)
    {
#ifdef _WIN32
        bool IsDirectory=true;

        FILE* TempFile=fopen(DirEntNames[DENr].c_str(), "r");
        if (TempFile!=NULL)
        {
            // This was probably a file (instead of a directory).
            fclose(TempFile);
            IsDirectory=false;
        }
#else
        bool IsDirectory=false;

        // Sigh. And this doesn't work under Win32... (opendir does not return NULL for files!?!)
        DIR* TempDir=opendir(DirEntNames[DENr].c_str());
        if (TempDir!=NULL)
        {
            // This was a directory.
            closedir(TempDir);
            IsDirectory=true;
        }
#endif

        if (IsDirectory)
        {
            if (Recurse)
                NewSoundShaders.PushBack(RegisterSoundShaderScriptsInDir(DirEntNames[DENr], ModDir));
        }
        else
        {
            if (DirEntNames[DENr].length()>5)
                if (std::string(DirEntNames[DENr].c_str()+DirEntNames[DENr].length()-5)==".caud")
                    NewSoundShaders.PushBack(RegisterSoundShaderScript(DirEntNames[DENr], ModDir));
        }
    }

    return NewSoundShaders;
}