Пример #1
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;
}
Пример #2
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);
}
Пример #3
0
/*----------------------------------------------------------------------*
                             rtp_wfile_gfirst
 *----------------------------------------------------------------------*/
int rtp_wfile_gfirst (void ** dirobj, unsigned short * name)
{
#if (_WIN32_WINNT) >= 0x0400
WFSOBJ* winDirObj;

#ifdef RTP_DEBUG
  
    SetLastError (0);
#endif

    winDirObj = (WFSOBJ*) malloc(sizeof(WFSOBJ));
    memset(winDirObj, 0, sizeof(WFSOBJ));

    name = _rtp_unicode_name_to_winname(name);
    winDirObj->fsObject.attrib = _A_NORMAL | _A_SUBDIR;
    winDirObj->handle = _wfindfirst((const unsigned short *) name, &(winDirObj->fsObject));
    if (winDirObj->handle == (long)(-1))
    {
        rtp_free (winDirObj);
#ifdef RTP_DEBUG
		RTP_DEBUG_OUTPUT_ERRNO("rtp_wfile_gfirst:");
#endif
        return (-1);
    }

    *dirobj = (void*) winDirObj;
    return (0);
#endif
	return (-1);
}
Пример #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;
}
Internal_Dir* Internal_Dir_Open(_In_z_ const TChar* path, NitsCallSite cs)
{
#if defined(_MSC_VER)

    Internal_Dir* dir;
    wchar_t filespec[PAL_MAX_PATH_SIZE];
    
    /* Allocate and zero-fill struct */
    dir = (Internal_Dir*)PAL_CallocCallsite(cs, 1, sizeof(Internal_Dir));
    if (!dir)
        return NULL;

    /* Build files spec */
    {
        if (Wcslcpy(filespec, path, PAL_MAX_PATH_SIZE) >= PAL_MAX_PATH_SIZE)
            return NULL;

        if (Wcslcat(filespec, L"/*", PAL_MAX_PATH_SIZE) >= PAL_MAX_PATH_SIZE)
            return NULL;
    }

    /* Find first file matching the file spec */
    dir->handle = _wfindfirst(filespec, &dir->fileinfo);
    if (dir->handle == -1)
    {
        PAL_Free(dir);
        return NULL;
    }

    /* Note that readdir() has not been called yet */
    dir->firstTime = 1;

    return dir;

#else

    Internal_Dir* self = (Internal_Dir*)PAL_CallocCallsite(cs, 1, sizeof(Internal_Dir));

    if (!self)
        return NULL;

    self->dir = opendir(path);
    if (!self->dir)
    {
        PAL_Free(self);
        return NULL;
    }
    memcpy(self->dirName, path, (Tcslen(path)+1) * sizeof(TChar));

    return self;

#endif          
}
Пример #6
0
void rewinddir(DIR *dir)
{
    if(dir && dir->handle != -1)
    {
        _findclose(dir->handle);
        dir->handle = (handle_type) _wfindfirst(dir->name, &dir->info);
        dir->result.d_name = 0;
    }
    else
    {
        errno = EBADF;
    }
}
Пример #7
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;
}
Пример #8
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 );
}
Пример #9
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;
}
Пример #10
0
bool OpFileSystem::IsFolder( const NrpText& pathTo )
{
    bool ret = false;
	NrpText myPath = RemoveEndSlash( pathTo );
	if( !IsExist( myPath ) )
        Log( HW ) << "Try delete unexisting file " << myPath << term;
	
	_wfinddata_t fdata;	
	intptr_t hFile;

	hFile = _wfindfirst( myPath, &fdata);
	if( hFile != -1 )
	{
		ret = ((( fdata.attrib & _A_SUBDIR ) == _A_SUBDIR ) || ( fdata.attrib == _A_SUBDIR ));// это папка
	}

    _findclose( hFile );

	return ret;
}
Пример #11
0
DIR *opendir(const wchar_t *name)
{
    DIR *dir = 0;

    if (!name || (0 == name[0])) {
        errno = ENOENT;
        return 0;
    }

    size_t base_len = wcslen(name);
    const wchar_t *all = /* search pattern must end with suitable wildcard */
        wcschr(L"/\\", name[base_len - 1]) ? L"*" : L"/*";

    dir = (DIR *) calloc(sizeof *dir, 1);
    dir->name = (wchar_t *)malloc((base_len + wcslen(all) + 1)*sizeof(wchar_t));
    if (!dir->name) {
        errno = ENOMEM;
        goto Error;
    }

    wcscat(wcscpy(dir->name, name), all);

    dir->handle = (handle_type) _wfindfirst(dir->name, &dir->info);
    if (dir->handle == -1) {
        struct _stat stat_buf = { 0 };
        int res = _wstat(name, &stat_buf);
        if (-1 == res) {
            errno = ENOENT;
            goto Error;
        }
        errno = ENOTDIR;
        goto Error;
    }
    dir->result.d_name = 0;
    return dir;
Error:
    if (dir)
        free(dir->name);
    free(dir);
    return 0;
}
Пример #12
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;
        }
	}
}
Пример #13
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);
}
Пример #14
0
fsal_dir_handle_t fsal_diropen(unsigned short *path) {
  long handle;
  struct _wfinddata_t filestruct;
  unsigned short real_path[READER_PATH_MAX] = {0};
  int i = 0;
  DIR_ITER *iter = NULL;

  iter = (DIR_ITER *)malloc(sizeof(*iter));
  if (iter == NULL) {
    return 0;
  }
  translate_path(path, real_path);
  reader_wcscpy(iter->path, real_path);
  reader_wcscat(real_path, L"\\*");
  handle = _wfindfirst(real_path, &filestruct);
  if (handle < 0) {
    READER_TRACEWM((L"real_path=%s\n", real_path));
    READER_TRACEM(("error in _wfindfirst():%d\n", errno));
    return 0;
  }
  iter->handle = handle;
  return (fsal_dir_handle_t)iter;
}
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;
}
Пример #16
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;
}
Пример #17
0
/*----------------------------------------------------------------------*
                             rtp_wfile_gfirst
 *----------------------------------------------------------------------*/
int rtp_wfile_gfirst (void ** dirobj, unsigned short * name)
{
#if (_WIN32_WINNT) >= 0x0400
WFSOBJ* winDirObj;

#ifdef RTP_DEBUG
    int result;
    /* ----------------------------------- */
    /*  Clear the error state by setting   */
    /*  to 0.                              */
    /* ----------------------------------- */
    SetLastError (0);
#endif

    winDirObj = (WFSOBJ*) malloc(sizeof(WFSOBJ));
    memset(winDirObj, 0, sizeof(WFSOBJ));

    name = _rtp_unicode_name_to_winname(name);
    winDirObj->fsObject.attrib = _A_NORMAL | _A_SUBDIR;
    winDirObj->handle = _wfindfirst((const unsigned short *) name, &(winDirObj->fsObject));
    if (winDirObj->handle == (long)(-1))
    {
        rtp_free (winDirObj);
#ifdef RTP_DEBUG
        result = GetLastError();
        RTP_DEBUG_OUTPUT_STR("rtp_wfile_gfirst: error returned ");
        RTP_DEBUG_OUTPUT_INT(result);
        RTP_DEBUG_OUTPUT_STR(".\n");
#endif
        return (-1);
    }

    *dirobj = (void*) winDirObj;
    return (0);
#endif
	return (-1);
}
bool CDirectorySearch::Init(std::string sDirectory)
{   // begin Init
    // check for no search query
    if(sDirectory[sDirectory.length()-1] == DIRECTORY_DELIMITOR)
    {
        printf("End with directory delimitor\n");
        return false;
    }

#ifdef __WIN32
    const char *old = sDirectory.c_str();

    int len = utf8StringToWideChar(old, -1, NULL);
    wchar_t s[len + 2];

    utf8StringToWideChar(old, -1, s);
    wcscat(s, L"\\*");

    printf(">%ls<\n", s);
#else
    const char *s = sDirectory.c_str();

    printf(">%s<\n",s);
#endif

    m_hSearch = _wfindfirst(s,&m_fdData);

    if(m_hSearch == -1)
    {
        printf("Find first failed\n");
        return false;
    }

    m_sDirectory = sDirectory;

    return true;
}// end Init
Пример #19
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;
}
Пример #21
0
/* al_findfirst:
 *  Initiates a directory search.
 */
int al_findfirst(AL_CONST char *pattern, struct al_ffblk *info, int attrib)
{
   struct FF_DATA *ff_data;
   char tmp[1024];

   /* allocate ff_data structure */
   ff_data = _AL_MALLOC(sizeof(struct FF_DATA));

   if (!ff_data) {
      *allegro_errno = ENOMEM;
      return -1;
   }

   /* attach it to the info structure */
   info->ff_data = (void *) ff_data;

   /* Windows defines specific flags for NTFS permissions:
    *   FA_TEMPORARY            0x0100
    *   FA_SPARSE_FILE          0x0200 
    *   FA_REPARSE_POINT        0x0400
    *   FA_COMPRESSED           0x0800
    *   FA_OFFLINE              0x1000
    *   FA_NOT_CONTENT_INDEXED  0x2000
    *   FA_ENCRYPTED            0x4000
    * so we must set them in the mask by default; moreover,
    * in order to avoid problems with flags added in the
    * future, we simply set all bits past the first byte.
    */
   ff_data->attrib = attrib | 0xFFFFFF00;

   /* start the search */
   errno = *allegro_errno = 0;

   if (get_filename_encoding() != U_UNICODE) {
      ff_data->handle = _findfirst(uconvert(pattern, U_CURRENT, tmp,
                                            U_ASCII, sizeof(tmp)),
                                            &ff_data->data.a);

      if (ff_data->handle < 0) {
         *allegro_errno = errno;
         _AL_FREE(ff_data);
         info->ff_data = NULL;
         return -1;
      }

      if (ff_data->data.a.attrib & ~ff_data->attrib) {
         if (al_findnext(info) != 0) {
            al_findclose(info);
            return -1;
         }
         else
            return 0;
      }
   }
   else {
      ff_data->handle = _wfindfirst((wchar_t*)uconvert(pattern, U_CURRENT, tmp,
                                                       U_UNICODE, sizeof(tmp)),
                                                       &ff_data->data.w);

      if (ff_data->handle < 0) {
         *allegro_errno = errno;
         _AL_FREE(ff_data);
         info->ff_data = NULL;
         return -1;
      }

      if (ff_data->data.w.attrib & ~ff_data->attrib) {
         if (al_findnext(info) != 0) {
            al_findclose(info);
            return -1;
         }
         else
            return 0;
      }
   }

   fill_ffblk(info);
   return 0;
}
Пример #22
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;
	}
Пример #23
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;
			}
        }
    }
Пример #24
0
#endif
{
#if defined(_MSC_VER)
	FindFileStruct 		theFindData;
	
	#ifdef _WIN64
		typedef	intptr_t	theHandleType;
	#else
		typedef	long	theHandleType;
	#endif

#pragma warning(push)
#pragma warning(disable: 4244)
	theHandleType	theSearchHandle =
        _wfindfirst(
            const_cast<wchar_t*>(theConversionFunction(theFullSearchSpec)),
			&theFindData);
#pragma warning(pop)

	if (theSearchHandle != -1)
	{
  
		try
		{
			do
			{
				if ((fIncludeSelfAndParent == true || theFindData.isSelfOrParent() == false) &&
					theFilterPredicate(theFindData) == true)
				{
					*theOutputIterator = StringType(theFindData.getName(), theMemoryManager);
				}
Пример #25
0
S32 btmtk_goep_fs_findfirst(U8 *ucFolderPath, bt_ftp_find_struct **findstruct, bt_ftp_obj_info_struct *ftp_file_info) {
#ifdef BTMTK_GOEP_USE_WIN32_FS
    char sdir[256];
    char filter[64];
    U32 test_arrtibe;
    struct _wfinddata_t c_file;
    long hFile;
    bt_ftp_find_struct *pfind;

    GOEP_MEMSET((U8 *)ftp_file_info, 0, sizeof(bt_ftp_obj_info_struct) );

    ext_ucs2_str_n_to_asc_str(sdir, ucFolderPath, sizeof(sdir));

    // keep the previous folder path
    g_oldcwd[0] = 0;
    if ( NULL == _wgetcwd( (U16 *)g_oldcwd, sizeof(g_oldcwd)/2 ) ) {
        /// cannot keep the current folder
        GOEP_Report("[FS][ERR] fail to get cwd bufsize:(%d) err:%d!", sizeof(g_oldcwd)/2, GetLastError());
        return EXT_FS_ERR;
    }

    printf( "[fs] getcwd is '%s'\n", g_oldcwd);
    printf( "[fs] fs findfirst '%s' \n", sdir );
    _wchdir( (U16 *) ucFolderPath );


    ext_strncpy (filter, "*.*", 64);
    hFile = _wfindfirst(L"*.*", &c_file);

    if( -1 == hFile ) {
        return EXT_FS_ERR;
    } else {
        //plong = (long * )malloc(sizeof(long));
        pfind = (bt_ftp_find_struct *) malloc( sizeof(bt_ftp_find_struct) );
        *findstruct = pfind;

        if( *findstruct == NULL ) {
            return EXT_FS_ERR;
        }
        ((bt_ftp_find_struct *)*findstruct)->hFile = hFile;

        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);
        test_arrtibe = (_A_SUBDIR & c_file.attrib);
        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
    U8 *filter;
    S32 hFile;
    S32 len;
    bt_ftp_find_struct *pfind;
    FS_DOSDirEntry dir_entry;
    U8 filename[ BTMTK_EP_MAX_FILENAME_LEN ]; /// output

    //ext_ucs2ncpy (filter, (const U8 *)L"\\*.*", sizeof(filter)/2);
    len = ext_ucs2strlen((const S8*)ucFolderPath)*2 + 10;
    filter = (U8 *) get_ctrl_buffer( len ); // plus L"\\*.*"
    if( NULL == filter ) {
        return EXT_FS_ERR;
    }
    btmtk_os_memset( filter, 0, len);
    ext_ucs2ncpy( (U8 *) filter,  (const U8 *) ucFolderPath , len-2);
    ext_ucs2ncat( (U8 *) filter, (const U8 *) L"\\*.*", len-2);

    ext_ucs2ncpy((S8 *)filename, (const U8 *)L"", (sizeof(filename)/2)-1);

    hFile = (S32) FS_FindFirst(
                (const WCHAR*)filter,
                0,
                0,
                &dir_entry,
                (U16*) filename,
                sizeof(filename) );
    if( NULL == filter ) {
        free_ctrl_buffer(filter);
        filter = NULL;
    }
    if ( hFile >= 0) {
        GOEP_MEMSET((U8 *)ftp_file_info, 0, sizeof(bt_ftp_obj_info_struct) );
        pfind = (bt_ftp_find_struct *) get_ctrl_buffer( sizeof(bt_ftp_find_struct) );
        *findstruct = pfind;
        if( *findstruct == NULL ) {
            FS_FindClose( (FS_HANDLE) hFile );
            return EXT_FS_ERR;
        }
        ((bt_ftp_find_struct *)*findstruct)->hFile = hFile;

        static_convert_DirEntry_to_file_info( &dir_entry, ftp_file_info , filename);

        return EXT_FS_OK;
    } else {
        return EXT_FS_ERR;
    }

#endif

#ifdef BTMTK_ON_LINUX

    int ret;
    int err_num;

    bt_ext_log("[GOEP_FS] btmtk_goep_fs_findfirst(): Linux Version.");

    ext_chset_ucs2_to_utf8_string((U8 *) g_folder_path, sizeof(g_folder_path)-1, ucFolderPath);
    // strncpy(g_folder_path, ucFolderPath, sizeof(g_folder_path));
    bt_ext_log("[GOEP_FS] g_folder_path: %s", g_folder_path);

    g_opened_dir = opendir( g_folder_path);
    if (g_opened_dir == NULL) {
        err_num = errno;
        bt_ext_err("[FS_ERR] opendir() failed. %s", (char*) strerror(err_num));
        return EXT_FS_ERR;
    }

    return static_linux_fill_file_info(ftp_file_info);

#endif

    return EXT_FS_ERR;
}
Пример #26
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
	}
Пример #27
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;
}