Ejemplo n.º 1
0
void YString::GetDirFiles(const wchar_t* dirPath, const wchar_t* suffix, std::vector<std::wstring>& filesPathVec)
{
	_wfinddata_t file;

	wchar_t dir[MAX_PATH_LEN];
	YString::Copy(dir, _countof(dir), dirPath);
	YString::Concat(dir, _countof(dir), L"/*.*");

	long handle = _wfindfirst(dir, &file);
	int k = handle;

	_wfindnext(handle, &file);
	_wfindnext(handle, &file);

	while(k != -1)
	{
		wchar_t fileSuffix[MAX_STR_LEN];
		YString::GetFileSuffix(fileSuffix, _countof(fileSuffix), file.name);

		if(YString::Compare(fileSuffix, suffix, true) == 0)
		{
			wchar_t filePath[MAX_PATH_LEN];
			YString::Copy(filePath, _countof(filePath), dirPath);
			YString::Concat(filePath, _countof(filePath), L"/");
			YString::Concat(filePath, _countof(filePath), file.name);

			filesPathVec.push_back(filePath);
		}

		k = _wfindnext(handle, &file);
	}

	_findclose(handle);
}
Ejemplo n.º 2
0
FolderEntries OpFileSystem::GetEntries( NrpText& pathToDir, bool fileOnly )
{
    _wfinddata_t fdata;	
    intptr_t hFile;

    FolderEntries ret;

    assert( pathToDir.size() );
    if( pathToDir.size() )
    {
        hFile = _wfindfirst( ( CheckEndSlash( pathToDir )+ anyFile ).ToWide(), &fdata);
        while( hFile )
        {
            NrpText absPath = CheckEndSlash( pathToDir )+ fdata.name;
            if ( !( firstEntry == fdata.name || secondEntry == fdata.name ) )// это удалять не надо
                if( !fileOnly && ((( fdata.attrib & _A_SUBDIR ) == _A_SUBDIR ) || ( fdata.attrib == _A_SUBDIR )) )// найдена папка
                    ret.push_back( FolderEntry( true, fdata.name, absPath ) );
                else// иначе найден файл
                    ret.push_back( FolderEntry( false, fdata.name, absPath ) );
 
                if( _wfindnext( hFile, &fdata) != 0 )
                    break;
        }
    }

    _findclose( hFile );

    return ret;
}
Ejemplo n.º 3
0
/*----------------------------------------------------------------------*
                             rtp_wfile_gnext
 *----------------------------------------------------------------------*/
int rtp_wfile_gnext (void * dirobj)
{
#if (_WIN32_WINNT) >= 0x0400
#ifdef RTP_DEBUG
    int result;
    /* ----------------------------------- */
    /*  Clear the error state by setting   */
    /*  to 0.                              */
    /* ----------------------------------- */
    SetLastError (0);
#endif

    if (_wfindnext (((WFSOBJ *)dirobj)->handle, &(((WFSOBJ *)dirobj)->fsObject)) != 0)
    {
#ifdef RTP_DEBUG
        result = GetLastError();
        RTP_DEBUG_OUTPUT_STR("rtp_wfile_gnext: error returned ");
        RTP_DEBUG_OUTPUT_INT(result);
        RTP_DEBUG_OUTPUT_STR(".\n");
#endif
        return (-1);
    }

    return (0);
#endif
	return (-1);
}
Ejemplo n.º 4
0
/**
 * @sa Sys_FindNext
 * @sa Sys_FindClose
 */
char* Sys_FindFirst (const char* path, unsigned musthave, unsigned canthave)
{
	struct _wfinddata_t findinfo;

	if (findhandle)
		Sys_Error("Sys_BeginFind without close");
	findhandle = 0;

	Com_FilePath(path, findbase, sizeof(findbase));
	Sys_Utf8ToUtf16(path, wfindpath, lengthof(wfindpath));
	findhandle = _wfindfirst(wfindpath, &findinfo);
	while (findhandle != -1) {
		/* found one that matched */
		Sys_Utf16ToUtf8(findinfo.name, findname, sizeof(findname));
		if (!Q_streq(findname, ".") && !Q_streq(findname, "..") &&
			CompareAttributes(findinfo.attrib, musthave, canthave)) {
			Com_sprintf(findpath, sizeof(findpath), "%s/%s", findbase, findname);
			return findpath;
		/* doesn't match - try the next one */
		} else if (_wfindnext(findhandle, &findinfo) == -1) {
			/* ok, no further entries here - leave the while loop */
			_findclose(findhandle);
			findhandle = -1;
		}
	}

	/* none found */
	return nullptr;
}
int CDirectorySearch::_wfindfirst(const char *path,_wfinddata_t *pfdData)
{   // begin _wfindfirst
    unsigned long int hDir = (unsigned long int)opendir(path);
    if(!hDir)
        return -1;
    if(_wfindnext(hDir,pfdData) == -1)
        return -1;
    return hDir;
}// end _wfindfirst
Ejemplo n.º 6
0
S32 btmtk_goep_fs_findnext(void *ptr , bt_ftp_obj_info_struct *ftp_file_info) {
#ifdef BTMTK_GOEP_USE_WIN32_FS
    long *plong;
    U32 test_arrtibe;
    struct _wfinddata_t c_file;

    if( NULL == ptr || NULL == ftp_file_info) {
        return EXT_FS_ERR;
    }

    plong = ptr;
    GOEP_MEMSET( (U8 *) ftp_file_info, 0, sizeof(bt_ftp_obj_info_struct) );
    if( 0 == _wfindnext( (long)*plong, &c_file ) ) {
        //ext_asc_str_n_to_ucs2_str( ftp_file_info->file_name, c_file.name, 260/2);
        ext_ucs2ncpy( (S8 *)ftp_file_info->file_name, (const S8 *)c_file.name, sizeof(ftp_file_info->file_name)/2 );
        update_win32_file_time(ftp_file_info);
        // ok. find the next
        test_arrtibe = (_A_SUBDIR & c_file.attrib);
        ftp_file_info->file_size = c_file.size;

        if( _A_SUBDIR == test_arrtibe  ) {
            ftp_file_info->isFile = FALSE;
        } else {
            ftp_file_info->isFile = TRUE;
        }

        return EXT_FS_OK;
    }
#endif

#ifdef BTMTK_ON_WISE
    FS_DOSDirEntry dir_entry;
    bt_ftp_find_struct *findstruct;
    U8 filename[ BTMTK_EP_MAX_FILENAME_LEN ];
    U8 ucfilename[ BTMTK_EP_MAX_FILENAME_LEN ];

    if( NULL != ptr ) {
        findstruct = (bt_ftp_find_struct *) ptr;
        if( 0 <= FS_FindNext( (FS_HANDLE) findstruct->hFile , &dir_entry, (U16 *) filename, sizeof(filename) ) ) {
            static_convert_DirEntry_to_file_info( &dir_entry, ftp_file_info , filename);

            memset( ucfilename, 0, sizeof( ucfilename) );
            ext_chset_ucs2_to_utf8_string( (U8 *)ucfilename, sizeof(ucfilename) - 1, (U8 *)filename );
            GOEP_Report("[ftp][fs] findnext file:(%s)", ucfilename);
            return EXT_FS_OK;
        }
    }
#endif

#ifdef BTMTK_ON_LINUX

    return static_linux_fill_file_info(ftp_file_info);

#endif

    return EXT_FS_ERR;
}
Internal_DirEnt* Internal_Dir_Read(_In_ Internal_Dir* self, _In_opt_z_ TChar *fileEndsWith)
{
    for(;;)
    {
#if defined(_MSC_VER)

        if (!self->firstTime)
        {
            if (_wfindnext(self->handle, &self->fileinfo) != 0)
                return NULL;
        }
        self->firstTime = 0;
        
        if( StringEndsWith(self->fileinfo.name, fileEndsWith) != 0 )
            continue;
        Wcslcpy(self->ent.name, self->fileinfo.name, PAL_MAX_PATH_SIZE);
        if( self->fileinfo.attrib & _A_SUBDIR )
            self->ent.isDir = 1;
        else
            self->ent.isDir = 0;
        
        return &self->ent;

#else
        struct dirent* p = readdir(self->dir);
        struct stat st;
        TChar filespec[PAL_MAX_PATH_SIZE];
        if (!p)
            return NULL;

        if( StringEndsWith(p->d_name, fileEndsWith) != 0 )
            continue;        

        Strlcpy(self->ent.name, p->d_name, PAL_MAX_PATH_SIZE);
        // Logic to detect Dir may not work on non-linux, non-windows platforms, in which case
        // We would need to use Isdir method.
        //self->ent.isDir = Isdir(self->ent.name);  
        if( Tcslcpy(filespec, self->dirName, PAL_MAX_PATH_SIZE) >= PAL_MAX_PATH_SIZE)
            return NULL;

        if( Tcslcat(filespec, "/", PAL_MAX_PATH_SIZE) >= PAL_MAX_PATH_SIZE)
            return NULL;

        if( Tcslcat(filespec, self->ent.name, PAL_MAX_PATH_SIZE) >= PAL_MAX_PATH_SIZE)
            return NULL;

        if (stat(filespec, &st) != 0)      
            return NULL;
        // self->ent.isDir = (p->d_type & DT_DIR) ? 1 : 0;
        self->ent.isDir = S_ISDIR(st.st_mode);
        return &self->ent;

#endif       
    }
}
Ejemplo n.º 8
0
std::vector<mmFileIO::mmFileUtilsI::sDirElement> mmOperatingSystem::GetDirectoryElements(mmString p_sDirName,
																																												 mmString p_sDirWildcards)
{
	std::vector<mmFileIO::mmFileUtilsI::sDirElement> v_sDirElements;
	_wfinddata_t v_sActFileInfo;
	mmFileIO::mmFileUtilsI::sDirElement v_sActElement;
	intptr_t v_hSearchHandle;
	int v_iRes = 0;

	// pobieram pierwszy element
	mmString v_sString((p_sDirName + mmString(L"\\") + p_sDirWildcards).c_str());
	v_hSearchHandle = _wfindfirst(const_cast<wchar_t*>(v_sString.c_str()), &v_sActFileInfo);
	if(v_hSearchHandle == -1)
	{
		//if( (_doserrno == ENOENT) || (_doserrno == EINVAL) )
		{
			throw mmError(mmeFileIONoSuchFileOrDirectory);
		}
		//else
		//{
		//	throw mmError(mmeUnknownError);
		//};
	}
	else
	{
		while(v_iRes != -1)
		{
			// przetwarzam element
			v_sActElement.sName = v_sActFileInfo.name;
			// nie przetwarzam elementów "." i ".."
			if( (v_sActElement.sName.compare(L".") != 0) && (v_sActElement.sName.compare(L"..") != 0) )
			{
				if(v_sActFileInfo.attrib & _A_SUBDIR)
				{
					v_sActElement.bFile = false;
				}
				else
				{
					v_sActElement.bFile = true;
				};
				v_sDirElements.push_back(v_sActElement);
			};
			// pobieram nastêpny
			v_iRes = _wfindnext(v_hSearchHandle,&v_sActFileInfo);
		};
	};

	_findclose(v_hSearchHandle);

	return v_sDirElements;
}
bool ResourceManager::LoadDirectory(ID2D1HwndRenderTarget* renderTarget, wchar_t * directoryName)
{
	intptr_t handle;
	int iResult = 0;
	bool bResult;
	_wfinddata_t fd;
	wchar_t buffer[128];

	wcscpy_s(buffer, directoryName);
	wcscat_s(buffer, L"\\*.*");

	handle = _wfindfirst(buffer, &fd);
	if (handle == -1)
		return false;

	while (!wcscmp(fd.name, L".") || !wcscmp(fd.name, L".."))
	{
		_wfindnext(handle, &fd);
	}

	while (iResult != -1)
	{
		wcscpy_s(buffer, directoryName);
		wcscat_s(buffer, L"\\");
		wcscat_s(buffer, fd.name);

		bResult = LoadFile(renderTarget, buffer);
		if (!bResult)
			return false;

		iResult = _wfindnext(handle, &fd);
	}

	_findclose(handle);

	return true;
}
Ejemplo n.º 10
0
void OpFileSystem::CreateDirectorySnapshot( const NrpText& directory, const NrpText& templateName,
											const NrpText& itemName, IniFile* ini, const NrpText& funcUpdate )
{
	_wfinddata_t fdata;	
	intptr_t hFile;

	assert( directory.size() );
	if( directory.size() )
	{
		hFile = _wfindfirst( ( CheckEndSlash( directory )+ anyFile ).ToWide(), &fdata);
		while( hFile )
		{
			if ( !( firstEntry == fdata.name || secondEntry == fdata.name ) )// это удалять не надо
				if ((( fdata.attrib & _A_SUBDIR ) == _A_SUBDIR ) || ( fdata.attrib == _A_SUBDIR ))// найдена папка
				{
					CreateDirectorySnapshot( CheckEndSlash( directory ) + NrpText( fdata.name ), templateName, itemName, ini, funcUpdate );
				}
				else// иначе найден файл
				{
					if( _wcsicmp( itemName.ToWide(), fdata.name ) == 0 )
					{
						NrpText fileName = CheckEndSlash( directory )+ fdata.name;
						IniFile rv( fileName );

						int number= ini->Get( SECTION_OPTIONS, templateName + numTemplate, (int)0 );

                        NrpText intName = rv.Get( SECTION_PROPERTIES, INrpConfig::uniqTemplate, NrpText( "" ) );
						ini->Set( SECTION_OPTIONS, CreateKeyName( number ), intName );
						ini->Set( SECTION_OPTIONS, templateName + NrpText( (int)number ), fileName );
						ini->Set( SECTION_OPTIONS, templateName + numTemplate, number+1 );

                        if( funcUpdate.size() && GetTickCount() - lastTimeUpdate > 500 )
                        {
                            lastTimeUpdate = GetTickCount();
                            CNrpScript::Instance().DoString( funcUpdate + "(" + NrpText( number ) + ")" );
                        }
					}
				}
			
			if( _wfindnext( hFile, &fdata) != 0 )
				break;
		}
	}

	_findclose( hFile );
}
Ejemplo n.º 11
0
struct dirent *readdir(DIR *dir)
{
    struct dirent *result = 0;

    if(dir && dir->handle != -1)
    {
        if(!dir->result.d_name || _wfindnext(dir->handle, &dir->info) != -1)
        {
            result         = &dir->result;
            result->d_name = dir->info.name;
        }
    }
    else
    {
        errno = EBADF;
    }

    return result;
}
Ejemplo n.º 12
0
/*----------------------------------------------------------------------*
                             rtp_wfile_gnext
 *----------------------------------------------------------------------*/
int rtp_wfile_gnext (void * dirobj)
{
#if (_WIN32_WINNT) >= 0x0400
#ifdef RTP_DEBUG
    SetLastError (0);
#endif

    if (_wfindnext (((WFSOBJ *)dirobj)->handle, &(((WFSOBJ *)dirobj)->fsObject)) != 0)
    {
#ifdef RTP_DEBUG
		RTP_DEBUG_OUTPUT_ERRNO("rtp_wfile_gnext:");
#endif
        return (-1);
    }

    return (0);
#endif
	return (-1);
}
Ejemplo n.º 13
0
static bool determineEntryCountAndWriteHeader(NexasPackage* package, const wchar_t* sourceDir, bool isBfeFormat) {
	writeLog(LOG_VERBOSE, L"Generating package header......");
	package->header = malloc(sizeof(Header));
	memcpy(package->header->typeTag, "PAC", 3);
	package->header->magicByte = 0;
	package->header->variantTag = isBfeFormat ? CONTENT_LZSS : CONTENT_MAYBE_DEFLATE;
	package->header->entryCount = 0;

	writeLog(LOG_VERBOSE, L"Moving into source directory......");
	if (_wchdir(sourceDir) != 0) {
		writeLog(LOG_QUIET, L"ERROR: Unable to read the source directory!");
		return false;
	}

	struct _wfinddata_t foundFile;
	intptr_t handle = _wfindfirst(L"*", &foundFile);
	int status = 0;
	while (status == 0) {
		if ((foundFile.attrib & _A_SUBDIR) == 0)
			++(package->header->entryCount);
		status = _wfindnext(handle, &foundFile);
	}
	_findclose(handle);

	writeLog(LOG_NORMAL, L"Found %u entries in the source directory.",
			package->header->entryCount);

	if (package->header->entryCount == 0) {
		writeLog(LOG_QUIET, L"ERROR: There is nothing to pack!");
		return false;
	}

	/// Write the header.
	if (fwrite(package->header, sizeof(Header), 1, package->file) != 1) {
		writeLog(LOG_QUIET, L"ERROR: Unable to write to the target package!");
		return false;
	}

	writeLog(LOG_VERBOSE, L"Package Header Written.");

	return true;
}
Ejemplo n.º 14
0
/**
 * @sa Sys_FindFirst
 * @sa Sys_FindClose
 */
char* Sys_FindNext (unsigned musthave, unsigned canthave)
{
	struct _wfinddata_t findinfo;

	if (findhandle == -1)
		return nullptr;

	/* until we found the next entry */
	while (_wfindnext(findhandle, &findinfo) != -1) {
		Sys_Utf16ToUtf8(findinfo.name, findname, sizeof(findname));
		if (!Q_streq(findname, ".") && !Q_streq(findname, "..") &&
			CompareAttributes(findinfo.attrib, musthave, canthave)) {
			Com_sprintf(findpath, sizeof(findpath), "%s/%s", findbase, findname);
			return findpath;
		}
	}

	/* none found */
	return nullptr;
}
Ejemplo n.º 15
0
void OpFileSystem::Remove( const NrpText& pathTo )
{
	if( !IsFolder( pathTo ) ) //файл можно удалить сразу
		DeleteFileW( pathTo.ToWide() );
	else
	{
		NrpText mStr = CheckEndSlash( pathTo );
		_wfinddata_t fdata;	
		intptr_t hFile;

		assert( IsExist( mStr ) );
		if( IsExist( mStr ) )
		{
			hFile = _wfindfirst( ( mStr + anyFile ).ToWide(), &fdata);
			while( hFile > 0 )
			{
				if ( !( firstEntry == fdata.name || secondEntry == fdata.name ) )// это удалять не надо
					if ((( fdata.attrib & _A_SUBDIR ) == _A_SUBDIR ) || ( fdata.attrib == _A_SUBDIR ))// найдена папка
					{
						Remove( CheckEndSlash( mStr ) + NrpText( fdata.name ) );
					}
					else// иначе найден файл
					{
						DeleteFileW( ( CheckEndSlash( mStr ) + fdata.name ).ToWide() );
					}

					if( _wfindnext( hFile, &fdata) != 0 )
						break;
			}

			_findclose( hFile );
		}

        if( !RemoveDirectoryW( RemoveEndSlash( mStr ).ToWide() ) )
        {
            int rr = GetLastError();
            rr = rr;
        }
	}
}
Ejemplo n.º 16
0
void Sys_ListFilteredFiles (const char* basedir, const char* subdirs, const char* filter, linkedList_t** list)
{
	char search[MAX_OSPATH], newsubdirs[MAX_OSPATH];
	char filename[MAX_OSPATH];
	int findhandle;
	struct _wfinddata_t findinfo;

	if (subdirs[0] != '\0') {
		Com_sprintf(search, sizeof(search), "%s\\%s\\*", basedir, subdirs);
	} else {
		Com_sprintf(search, sizeof(search), "%s\\*", basedir);
	}

	Sys_Utf8ToUtf16(search, wfindpath, lengthof(wfindpath));
	findhandle = _wfindfirst(wfindpath, &findinfo);
	if (findhandle == -1)
		return;

	do {
		Sys_Utf16ToUtf8(findinfo.name, findname, sizeof(findname));
		if (findinfo.attrib & _A_SUBDIR) {
			if (Q_strcasecmp(findname, ".") && Q_strcasecmp(findname, "..")) {
				if (subdirs[0] != '\0') {
					Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s\\%s", subdirs, findname);
				} else {
					Com_sprintf(newsubdirs, sizeof(newsubdirs), "%s", findname);
				}
				Sys_ListFilteredFiles(basedir, newsubdirs, filter, list);
			}
		}
		Com_sprintf(filename, sizeof(filename), "%s\\%s", subdirs, findname);
		if (!Com_Filter(filter, filename))
			continue;
		LIST_AddString(list, filename);
	} while (_wfindnext(findhandle, &findinfo) != -1);

	_findclose(findhandle);
}
Ejemplo n.º 17
0
void OpFileSystem::Copy( const NrpText& pathOld, const NrpText& pathNew )
{
	NrpText newfile;
	intptr_t hFile;

	if( !IsExist( pathNew ) )
		CreateDirectory( pathNew );

	_wfinddata_t fdata;
	assert( IsExist( pathOld ) );
	if( IsExist( pathOld ) )
	{
		hFile = _wfindfirst( ( CheckEndSlash( pathOld )+ anyFile ).ToWide(), &fdata);
		while( hFile > 0 )
		{
			if ( fdata.attrib & _A_SUBDIR )  // если нашли папку
			{
				if( !( firstEntry == fdata.name || secondEntry == fdata.name ) )
				{
					Copy( CheckEndSlash( pathOld ) + NrpText( fdata.name ),
						  CheckEndSlash( pathNew ) + NrpText( fdata.name ) );// Рекурсивный вызов
				}
			}
			else // если нашли файл
			{
				newfile = CheckEndSlash( pathNew ) + fdata.name;
			    CopyFileW( ( CheckEndSlash( pathOld ) + fdata.name ).ToWide(), newfile.ToWide(), true);
			}

			if( _wfindnext( hFile, &fdata) != 0 )
				break;
		}

		_findclose( hFile );
	}
	return;
}
Ejemplo n.º 18
0
int fsal_dirnext(fsal_dir_handle_t hdir, unsigned short *filename, struct stat *st) {
  DIR_ITER *dir = (DIR_ITER *)hdir;
  int ret;
  struct _wfinddata_t filestruct;
  unsigned short fullname[READER_PATH_MAX];

  ret = _wfindnext(dir->handle,&filestruct);
  if (ret != 0) {
    return ret;
  }
  //do not return '.' and '..' entries for simulated root dir
  if ((wcscmp(dir->path, root_dir_uni) == 0) //is root dir
   && ((wcscmp(filestruct.name, reader_path_this) == 0)
   || ((wcscmp(filestruct.name, reader_path_upper) == 0)))
   ) {
    return fsal_dirnext((fsal_dir_handle_t)dir, filename, st);
  }
  reader_wcscpy(filename, filestruct.name);
  reader_wcscpy(fullname, dir->path);
  reader_wcscat(fullname, L"\\");
  reader_wcscat(fullname, filename);
  //"struct stat" and "struct _stat" are identical
  return _wstat(fullname, (struct _stat *)st);
}
Ejemplo n.º 19
0
/* al_findnext:
 *  Retrieves the next file from a directory search.
 */
int al_findnext(struct al_ffblk *info)
{
   struct FF_DATA *ff_data = (struct FF_DATA *) info->ff_data;

   if (get_filename_encoding() != U_UNICODE) {
      do {
         if (_findnext(ff_data->handle, &ff_data->data.a) != 0) {
            *allegro_errno = errno;
            return -1;
         }
      } while (ff_data->data.a.attrib & ~ff_data->attrib);
   }
   else {
      do {
         if (_wfindnext(ff_data->handle, &ff_data->data.w) != 0) {
            *allegro_errno = errno;
            return -1;
         }
      } while (ff_data->data.w.attrib & ~ff_data->attrib);
   }

   fill_ffblk(info);
   return 0;
}
Ejemplo n.º 20
0
/* al_findnext:
 *  Retrieves the next file from a directory search.
 */
int al_findnext(struct al_ffblk *info)
{
   struct FF_DATA *ff_data = (struct FF_DATA *) info->ff_data;

   if (!_al_win_unicode_filenames) {
      do {
         if (_findnext(ff_data->handle, &ff_data->data.a) != 0) {
            *allegro_errno = errno;
            return -1;
         }
      } while (ff_data->data.a.attrib & ~ff_data->attrib);
   }
   else {
      do {
         if (_wfindnext(ff_data->handle, &ff_data->data.w) != 0) {
            *allegro_errno = errno;
            return -1;
         }
      } while (ff_data->data.w.attrib & ~ff_data->attrib);
   }

   fill_ffblk(info);
   return 0;
}
Ejemplo n.º 21
0
void xhn::wpath_node::search(const wchar_t* path)
{
	path_name = path;
	transform(path_name.begin(), path_name.end(), path_name.begin(), FWCharFormat());
    wstring search_path = path_name;
#if defined(_WIN32) || defined(_WIN64)
	if (search_path.size() && search_path[search_path.size() - 1] != L'\\') {
		search_path += L'\\';
	}
#elif defined(__APPLE__)
    if (search_path.size() && search_path[search_path.size() - 1] != L'/') {
		search_path += L'/';
	}
#else
#    error
#endif
#if defined(_WIN32) || defined(_WIN64)
	wstring tmp = search_path +  L"*";

	struct _wfinddata_t fd;
	long h = _wfindfirst(tmp.c_str(), &fd);
	int ret = 0;
	while (h != -1L && !ret)
	{
		if (StrCmpW(fd.name, L".") != 0 && StrCmpW(fd.name, L"..") != 0)
		{
			wpath_node_ptr child;
#ifdef USE_SMART_PTR
            child = VNEW wpath_node;
#else
            child = GC_ALLOC(wpath_node);
#endif
			child->search((search_path + fd.name).c_str());
			if (fd.attrib == 0x10) {
			    child->is_folder = true;
			}
			child->next = children;
			children = child;
		}
		ret = _wfindnext(h, &fd);
	}
	_findclose(h);
#elif defined(__APPLE__)
    Utf8 utf8(search_path.c_str());
    vector<string> subFolders;
    vector<string> paths;
    GetPaths(((string)utf8).c_str(), subFolders, paths);
    {
        vector<string>::iterator iter = subFolders.begin();
        vector<string>::iterator end = subFolders.end();
        for (; iter != end; iter++) {
            string& subFolder = *iter;
            Unicode uc16(subFolder.c_str());
            wpath_node_ptr child;
#ifdef USE_SMART_PTR
            child = VNEW wpath_node;
#else
            child = GC_ALLOC(wpath_node);
#endif
            child->search(((wstring)uc16).c_str());
            child->is_folder = true;
            child->next = children;
			children = child;
        }
    }
    {
        vector<string>::iterator iter = paths.begin();
        vector<string>::iterator end = paths.end();
        for (; iter != end; iter++) {
            string& path = *iter;
            Unicode uc16(path.c_str());
            wpath_node_ptr child;
#ifdef USE_SMART_PTR
            child = VNEW wpath_node;
#else
            child = GC_ALLOC(wpath_node);
#endif
            child->path_name = uc16;
            child->is_folder = false;
            child->next = children;
			children = child;
        }
    }
#else
#    error
#endif
}
//----------------------------------------------------------------------------//
size_t DefaultResourceProvider::getResourceGroupFileNames(
    std::vector<String>& out_vec,
    const String& file_pattern,
    const String& resource_group)
{
    // look-up resource group name
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resource_group.empty() ? d_defaultResourceGroup :
                              resource_group);
    // get directory that's set for the resource group
    const String dir_name(
        iter != d_resourceGroups.end() ? (*iter).second : "./");

    size_t entries = 0;

// Win32 code.
#if defined(__WIN32__) || defined(_WIN32)
    intptr_t f;
    struct _wfinddata_t fd;

    if ((f = _wfindfirst(System::getStringTranscoder().stringToStdWString(
            dir_name + file_pattern).c_str(), &fd)) != -1)
    {
        do
        {
            if ((fd.attrib & _A_SUBDIR))
                continue;

            out_vec.push_back(System::getStringTranscoder().stringFromStdWString(fd.name));
            ++entries;
        }
        while (_wfindnext(f, &fd) == 0);

        _findclose(f);
    }

// Everybody else
#else
    DIR* dirp;

    if ((dirp = opendir(dir_name.c_str())))
    {
        struct dirent* dp;

        while ((dp = readdir(dirp)))
        {
            const String filename(dir_name + dp->d_name);
            struct stat s;

            if ((stat(filename.c_str(), &s) == 0) &&
                    S_ISREG(s.st_mode) &&
                    (fnmatch(file_pattern.c_str(), dp->d_name, 0) == 0))
            {
                out_vec.push_back(dp->d_name);
                ++entries;
            }
        }

        closedir(dirp);
    }
#endif

    return entries;
}
Ejemplo n.º 23
0
	FileInfoSeq PathUtil::getFileInfos(const String& base, const String& path, const String& filters, int flags) {
		FileInfoSeq fileinfos;
		_wfinddata_t finddata;
		long handle;
		int num_files = 0;
		size_t baselen = base.length();

		Filter filter(filters);

		String pattern = path;
		if (!PathUtil::isDirectoryLetter(pattern[pattern.length() - 1])) {
			pattern += '/';
		}
		pattern += '*';

		handle = _wfindfirst(const_cast<wchar_t *>(u2w(pattern).c_str()), &finddata);
		if (handle == -1) {
			_findclose(handle);
			return fileinfos;
		}

		do {
			FileInfo info;
			if (finddata.attrib & _A_SUBDIR) {
				if (!wcscmp(finddata.name, L".") || !wcscmp(finddata.name, L"..")) {
					continue;
				}

				if (!(flags & File::List_needCVS)) {
					if (!wcscmp(finddata.name, L"CVS")) {
						continue;
					}
				}

				if (flags & File::List_nodirectory) {
					continue;
				}

				if (flags & File::List_filterDirectory) {
					if (!filter.In(w2u(finddata.name)))
						continue;
				}

				info.isDir = true;
			} else {
				if (flags & File::List_nofile) {
					continue;
				}

				if (!(flags & File::List_nofilterfile)) {
					if (!filter.In(w2u(finddata.name)))
						continue;
				}

				info.isDir = false;
			}

			info.fullpath = (path + "/" + w2u(finddata.name)).c_str() + baselen;
			info.filetype = File::Stdio;
			info.filesize = finddata.size;
			info.filetime = finddata.time_write;
			info.localtime = *_localtime64(&finddata.time_write);

			PathUtil::splitPath(info.fullpath, info.filepath, info.filename, info.fileext);
			info.filename = PathUtil::removeDir(info.fullpath);

			fileinfos.push_back(info);

			num_files++;

		} while (_wfindnext(handle, &finddata) != -1);

		_findclose(handle);

		if (flags & File::List_sort) {
			std::sort(fileinfos.begin(), fileinfos.end(), CmpFileInfoNameLess);
		}

		return fileinfos;
	}
Ejemplo n.º 24
0
	//-----------------------------------------------------------------------
	void UnicodeFileSystemArchive::FileFinder::_run(const String& _dir, const WString& _wFullDir)
	{
		wchar_t wFindPattern[MAX_PATH];
		wcscpy(wFindPattern, _wFullDir.c_str());
		wcscpy(&wFindPattern[_wFullDir.length()], L"*");
       
        long lHandle;
		struct _wfinddata_t wTagData;
        lHandle = _wfindfirst(wFindPattern, &wTagData);

		String  tagDataName;
		String  dir2;
		WString wFullDir2;

		while(lHandle != -1)
		{
			bool isSubDir = ((wTagData.attrib & _A_SUBDIR) != 0);
			bool isHidden = ((wTagData.attrib & _A_HIDDEN) != 0);
			if((!mIgnoreHidden || !isHidden)
				&& !isReservedDir(wTagData.name)
				&& ((isSubDir == mDirs) || (isSubDir && mRecursive)))
			{
				tagDataName = mArchive->toString(wTagData.name);

				if(isSubDir == mDirs
					&& (mMask.empty() || StrUtil::match(tagDataName, mMask)))
				{
					if (mSimpleList)
					{
						mSimpleList->push_back(String());
						String& back = mSimpleList->back();
						back = _dir;
						back += tagDataName;
					}
					else if (mDetailList)
					{
						FileInfo fi;
						fi.archive = mArchive;
						fi.filename = _dir;
						fi.filename += tagDataName;
						fi.basename = tagDataName;
						fi.path = _dir;
						fi.compressedSize = wTagData.size;
						fi.uncompressedSize = wTagData.size;
						mDetailList->push_back(fi);
					}
				}

				if(isSubDir && mRecursive)
				{
					dir2 = _dir;
					dir2 += tagDataName;
					dir2 += '/';
					
					wFullDir2 = _wFullDir;
					wFullDir2 += wTagData.name;
					wFullDir2 += '/';
					
					_run(dir2, wFullDir2);
				}
			}
			
			if(_wfindnext( lHandle, &wTagData ) == -1)
			{
				_findclose(lHandle);
				lHandle = -1;
			}
        }
    }
Ejemplo n.º 25
0
	void Directory::_VisitDirectory(const String& path, const String& pattern,
		const String& subPath, ScanCallback* callback, bool recursive) {
		FileAttribute attr;

		String fullPath;
		fullPath = path;
		if (subPath.length())
			fullPath = URL::GetAppendedPath(fullPath, subPath);
		else
			fullPath = path;
#if defined(NEX_MSVC)
		if (pattern.length())
			fullPath = URL::GetAppendedPath(fullPath, pattern);

		UniString fullPathUni = StringUtils::ToUtf16(fullPath);
		intptr_t fileHandle, res;
		struct _wfinddata_t data;
		fileHandle = _wfindfirst((const wchar_t*)fullPathUni.c_str(), &data);
		res = 0;
		while (fileHandle != -1 && res != -1) {
			String utf8path = StringUtils::ToUtf8((const char16_t*)data.name);
			String fullPath = URL::GetAppendedPath(path, utf8path);
			attr.fileName = URL(GetName(), URL::GetAppendedPath(subPath, utf8path));
			attr.flags = 0;
			if ((data.attrib & _A_SUBDIR)) {
				if ((!URL::IsReservedPath(utf8path.c_str())) && recursive)
					_VisitDirectory(fullPath, pattern, attr.fileName.GetRelativePath(), callback, true);
				attr.flags = FileAttribute::ATTRIB_DIR;
			}
			else if (data.attrib * _A_ARCH)
				attr.flags = FileAttribute::ATTRIB_ARC;
			if (data.attrib * _A_RDONLY)
				attr.flags |= FileAttribute::ATTRIB_READONLY;
			NEX_SET_FILE_TIME(attr.fileTime, data.time_write);
			attr.compressedSize = data.size;
			attr.uncompressedSize = data.size;
			callback->FoundFile(attr, this);
			res = _wfindnext(fileHandle, &data);
		}

		if (fileHandle != -1)
			_findclose(fileHandle);
#elif defined(NEX_GCC)
		/** todo Fix this */
		DIR *dp;
		struct dirent *dirp;
		fullPath = path + "/" + subPath;

		dp = opendir(fullPath.c_str());
		if (dp) {
			while ((dirp = readdir(dp)) != NULL) {
				if (!pattern.length()
					|| StringUtils::PatternMatch(pattern.c_str(), dirp->d_name,
					true)) {
					String fullPathName = URL::GetAppendedPath(fullPath, dirp->d_name);
					attr.fileName = URL(GetName(),
						URL::GetAppendedPath(subPath, dirp->d_name));
					attr.flags = 0;
					struct stat filestat;
					int ret = stat(fullPathName.c_str(), &filestat);
					if (ret == 0)
						StatToAttribute(filestat, attr);
					callback->FoundFile(attr, this);
					if (recursive && (attr.flags & FileAttribute::ATTRIB_DIR)
						&& !URL::IsReservedPath(dirp->d_name))
						_VisitDirectory(fullPath, pattern,
						attr.fileName.GetRelativePath(), callback,
						true);
				}
			}
			closedir(dp);
		}
#endif
	}
Ejemplo n.º 26
0
static bool recordAndWriteEntries(NexasPackage* package, bool isBfeFormat) {
	package->indexes = newByteArray(package->header->entryCount * sizeof(IndexEntry));
	IndexEntry* indexes = (IndexEntry*)baData(package->indexes);

	u32 i = 0;
	u32 offset = 12;

	if (isBfeFormat) {
		/// This PAC Variant puts index first, but now we do not know
		/// the index, so we reserve the space.
		u32 len = baLength(package->indexes);
		for (u32 i = 0; i < len; ++i) {
			if (fputc('\0', package->file) == EOF) {
				writeLog(LOG_QUIET, L"ERROR: Unable to reserve space for the index!");
				return false;
			}
		}
		offset += len;
	}

	struct _wfinddata_t foundFile;
	intptr_t handle = _wfindfirst(L"*", &foundFile);
	int status = 0;
	while (status == 0) {
		if ((foundFile.attrib & _A_SUBDIR) == 0) {
			char* fname = toMBString(foundFile.name, L"japanese");
			if (strlen(fname) >= 64) {
				writeLog(LOG_QUIET, L"ERROR: Entry %u: %s, The file name is too long!", i, foundFile.name);
				free(fname);
				return false;
			}
			strncpy(indexes[i].name, fname, 64);
			free(fname);

			indexes[i].encodedLen = foundFile.size;
			indexes[i].decodedLen = foundFile.size;
			indexes[i].offset = offset;
			writeLog(LOG_VERBOSE, L"Entry %u: %s, Offset: %u, OLen: %u",
					i, foundFile.name, indexes[i].offset, indexes[i].decodedLen);

			FILE* infile = _wfopen(foundFile.name, L"rb");
			byte* decodedData = malloc(indexes[i].decodedLen);

			if (fread(decodedData, 1, indexes[i].decodedLen, infile) != indexes[i].decodedLen) {
				writeLog(LOG_QUIET, L"ERROR: Entry %u: %s, Unable to read the file!", i, foundFile.name);
				free(decodedData);
				fclose(infile);
				return false;
			}
			fclose(infile);

			byte* encodedData = NULL;
			ByteArray* encodedArray = NULL;

			if (isBfeFormat) {
				encodedArray = lzssEncode(decodedData, indexes[i].decodedLen);
				encodedData = baData(encodedArray);
				indexes[i].encodedLen = baLength(encodedArray);
			} else if (shouldZip(foundFile.name)) {
				encodedData = malloc(indexes[i].decodedLen);
				unsigned long len = indexes[i].encodedLen;
				if (compress(encodedData, &len, decodedData, indexes[i].decodedLen) != Z_OK) {
					free(encodedData);
					free(decodedData);
					return false;
				}
				indexes[i].encodedLen = len;
				writeLog(LOG_VERBOSE, L"Entry %u is compressed: ELen: %u", i, len);
			} else {
				encodedData = decodedData;
			}
			offset += indexes[i].encodedLen;
			writeLog(LOG_VERBOSE, L"Entry %u: ELen: %u", i, indexes[i].encodedLen);

			if (fwrite(encodedData, 1, indexes[i].encodedLen, package->file) != indexes[i].encodedLen) {
				writeLog(LOG_QUIET, L"ERROR: Entry %u: %s, Unable to write to the package!", i, foundFile.name);
				if (encodedArray != NULL) {
					deleteByteArray(encodedArray);
				} else if (encodedData != decodedData) {
					free(encodedData);
				}
				free(decodedData);
				return false;
			}

			if (encodedArray != NULL) {
				deleteByteArray(encodedArray);
			} else if (encodedData != decodedData) {
				free(encodedData);
			}
			free(decodedData);

			writeLog(LOG_NORMAL, L"Packed: Entry %u: %s.", i, foundFile.name);
			++i;
		}
		status = _wfindnext(handle, &foundFile);
	}
	_findclose(handle);
	return true;
}