示例#1
1
	bool CFileSystem::FileExists( const string_t& fileName ) {
		IFile* file = this->OpenFile( fileName, fileMode_Read );
		if ( file ) { 
			file->Close();
			SafeDelete(file);
			return true; 
		} else 
			return false;
	}
示例#2
0
bool
CConfigFile::Load(const char* filename, IFileSystem& fs)
{
    m_sections.erase(m_sections.begin(), m_sections.end());

    // open the file
    IFile* file = fs.Open(filename, IFileSystem::read);
    if (file == NULL) {
        return false;
    }

    std::string current_section = "";

    bool eof = false;
    while (!eof) {
        // read a line
        std::string line;
        eof = !read_line(file, line);
        const char* string = line.c_str();

        // parse it

        // eliminate whitespace
        skip_whitespace(string);

        if (string[0] == '[') {  // it's a section
            string++;

            current_section = "";
            while (*string != ']') {
                current_section += *string++;
            }
            string++;
        } else {                 // it's a key=value pair

            // read key
            std::string key;
            while (*string != '=' && *string) {
                key += *string++;
            }

            if (*string == 0) {
                continue; // skip lines without equals
            }
            string++; // skip the '='

            std::string value;
            while (*string) {
                value += *string++;
            }

            // add the item
            WriteString(current_section.c_str(), key.c_str(), value.c_str());
        }
    }

    file->Close();
    return true;
}
示例#3
0
文件: pck.cpp 项目: JonnyH/OpenApoc
static sp<PaletteImage> loadShadowImage(IFile &file, uint8_t shadedIdx)
{
	struct ShadowHeader header;
	file.read(reinterpret_cast<char *>(&header), sizeof(header));
	if (!file)
	{
		LogError("Unexpected EOF reading shadow PCK header\n");
		return nullptr;
	}
	auto img = mksp<PaletteImage>(Vec2<int>{header.width, header.height});
	PaletteImageLock region(img);

	uint8_t b = 0;
	file.read(reinterpret_cast<char *>(&b), 1);
	int pos = 0;
	while (b != 0xff)
	{
		uint8_t count = b;
		file.read(reinterpret_cast<char *>(&b), 1);
		if (!file)
		{
			LogError("Unexpected EOF reading shadow data\n");
			return nullptr;
		}
		uint8_t idx = b;

		if (idx == 0)
			pos += count * 4;
		else
		{
			LogAssert(idx < 7);

			while (count--)
			{
				for (int i = 0; i < 4; i++)
				{
					const int STRIDE = 640;
					int x = pos % STRIDE;
					int y = pos / STRIDE;
					if (x < header.width && y < header.height)
					{
						if (ditherLut[idx][i])
							region.set({x, y}, shadedIdx);
						else
							region.set({x, y}, 0);
					}
					pos++;
				}
			}
		}
		file.read(reinterpret_cast<char *>(&b), 1);
		if (!file)
		{
			LogError("Unexpected EOF reading shadow data\n");
			return nullptr;
		}
	}
	return img;
}
示例#4
0
std::string CFileCache::GetContentCharset(void)
{
  IFile* impl = m_source.GetImplemenation();
  if (!impl)
    return IFile::GetContentCharset();

  return impl->GetContentCharset();
}
BOOL KSkillManager::LoadSkillBinaryData(KMAP_SKILL_DATA& allBinarySkillData)
{
    BOOL                bResult         = false;
    BOOL                bRetCode        = false;
    IFile*              piFile          = NULL;
    BYTE*               pBuffer         = NULL;
    size_t              uBufferSize     = 0;
    uint64_t            uSkillKey       = 0;
    KSkillBinaryData*   pBinaryData     = NULL;
    KAnchor*            pAnchor         = NULL;
    KSkillSegmentInfo*  pSegmentInfo    = NULL;
    KSkillLogicInfo*    pLogicData      = NULL;
    unsigned int        uEnd            = 0;
    BYTE*               pBufferEnd      = NULL;

    piFile = g_OpenFile(SETTING_DIR"/SkillAction.skilllogic");
    KGLOG_PROCESS_ERROR(piFile);

    pBuffer = (BYTE*)piFile->GetBuffer();
    KGLOG_PROCESS_ERROR(pBuffer);

    uBufferSize = piFile->Size();
    KGLOG_PROCESS_ERROR(uBufferSize);

    bRetCode = g_DoBufferSkip(pBuffer, uBufferSize, sizeof(KSkillLogicFileHeader));
    KG_PROCESS_ERROR(bRetCode);

    while (uBufferSize)
    {
        bRetCode = g_ReadFromBufferTo(pBuffer, uBufferSize, uEnd);
        KGLOG_PROCESS_ERROR(bRetCode);

        pBufferEnd = pBuffer + uEnd;

        bRetCode = g_ReadFromBufferAs(pBuffer, uBufferSize, pLogicData);
        KGLOG_PROCESS_ERROR(bRetCode);

        uSkillKey = MAKE_INT64(pLogicData->skillID, pLogicData->skillStep);
        pBinaryData = &allBinarySkillData[uSkillKey];

        pBinaryData->dwID           = pLogicData->skillID;
        pBinaryData->dwStep         = pLogicData->skillStep;
        pBinaryData->nTotalFrame    = pLogicData->frameCount;

        bRetCode = LoadAnchors(pBuffer, uBufferSize, pBinaryData->Anchors);
        KGLOG_PROCESS_ERROR(bRetCode);

        bRetCode = LoadSegments(pBuffer, uBufferSize, pBinaryData->Segments);
        KGLOG_PROCESS_ERROR(bRetCode);

        KGLOG_PROCESS_ERROR(pBufferEnd == pBuffer);
    }

    bResult = true;
Exit0:
    KG_COM_RELEASE(piFile);
    return bResult;
}
示例#6
0
	char* Workspace::ReadFileToBuffer(const char* file, uint32_t& bufferSize)
    {
        IFile* fp = behaviac::CFileManager::GetInstance()->FileOpen(file, CFileSystem::EOpenAccess_Read);

        if (!fp)
        {
            return 0;
        }

        //fp->Seek(0, CFileSystem::ESeekMoveMode_End);
        uint32_t fileSize = (uint32_t)fp->GetSize();

		bufferSize = fileSize + 1;

		char* pBuffer = 0;

		for (int i = 0; i < kFileBuffers; ++i) {
			FileBuffer_t& fileBuffer = this->m_fileBuffers[i];
			BEHAVIAC_ASSERT(fileBuffer.offset == 0 || fileBuffer.offset < fileBuffer.length);

			if (fileBuffer.start == 0) {
				//to allocate extra 10k
				int fileBufferLength = bufferSize + 10 * 1024;

				const int kBufferLength = 100 * 1024;

				if (fileBufferLength < kBufferLength) {
					fileBufferLength = kBufferLength;
				}

				fileBuffer.start = (char*)BEHAVIAC_MALLOC(fileBufferLength);
				fileBuffer.length = fileBufferLength;
				BEHAVIAC_ASSERT(fileBuffer.offset == 0);

				pBuffer = fileBuffer.start;
				fileBuffer.offset += bufferSize;
				BEHAVIAC_ASSERT(fileBuffer.offset < fileBuffer.length);

				break;
			}
			else if (bufferSize  < fileBuffer.length - fileBuffer.offset) {
				pBuffer = fileBuffer.start + fileBuffer.offset;
				fileBuffer.offset += bufferSize;
				BEHAVIAC_ASSERT(fileBuffer.offset < fileBuffer.length);

				break;
			}
		}

		BEHAVIAC_ASSERT(pBuffer);

        fp->Read(pBuffer, sizeof(char) * fileSize);
        pBuffer[fileSize] = 0;

        behaviac::CFileManager::GetInstance()->FileClose(fp);

        return pBuffer;
    }
示例#7
0
bool KLuaWrap::DoScriptFile(const char *ScriptFile, const char *EnvName /*= NULL*/)
{
	bool ret = false;
	assert(m_L);
	if (!(ScriptFile && ScriptFile[0]))
		return false;

	IFile*	pFile = NULL;
	char*	pBuffer = NULL;
	unsigned int	size;

	if ((pFile = g_OpenFile(ScriptFile)) == NULL)
	{
		printf("%s is not exist!\n", ScriptFile);
		KGLogPrintf(KGLOG_WARNING, "[Lua] %s is not exist!\n", ScriptFile);
		return false;
	}

	size = pFile->Size();
	pBuffer = (char*)malloc(size + 1024);
	if (pBuffer)
	{
		char tmp[128];
		int pos = 0;
		int tmpLen = sprintf(tmp, "package.path = \"%s?.lua\"", m_ScriptPackagePath);
#ifdef WIN32
		for (int i = 0; i < tmpLen; ++i)
		{
			pBuffer[pos++] = tmp[i];
			if (tmp[i] == '\\')
			{
				pBuffer[pos++] = '\\';
			}
		}
#endif
		if (EnvName && EnvName[0])
			pos += sprintf(pBuffer + pos, "%s={} setmetatable(%s,{__index=_G,__newindex=function(t,i,v)for _,r in pairs(_RESERVE_G_VAR_)do if i==r then _G[i] = v return end end rawset(t,i,v)end}) setfenv(1,%s)", EnvName, EnvName, EnvName);

		if (pFile->Read(pBuffer + pos, size) == size)
		{
			ret = lua_tinker::dobuffer(m_L, pBuffer, size + pos, ScriptFile);
			if (ret && EnvName && EnvName[0])
			{
				lua_getglobal(m_L, EnvName);
				lua_pushstring(m_L, "CURRENT_SCRIPT_FILE");
				lua_pushstring(m_L, ScriptFile);
				lua_settable(m_L, -3);
				lua_pop(m_L, 1);
			}
		}
		free(pBuffer);
		pBuffer = NULL;
	}

	pFile->Release();
	pFile = NULL;
	return ret;
}
//-------------------------------------------------------------------------------------------------
void FrmFileExplorer::saveActiveFileAs(const QString &sFile)
{
    IFile *pActiveFile = getActiveFile();
    if (pActiveFile!=NULL)
    {
        pActiveFile->setPath(sFile);
        pActiveFile->save();
    }
}
示例#9
0
bool FuncSumHills::checkFilesAreExisting(const vector<string> & hills ){
	plumed_massert(hills.size()!=0,"the number of  files provided should be at least one" );
        IFile *ifile = new IFile();
        ifile->link(*this);
        for(unsigned i=0; i< hills.size();i++){  
          plumed_massert(ifile->FileExist(hills[i]),"missing file "+hills[i]);
        }
        return true; 

}
示例#10
0
// Close the File.
VFS_BOOL VFS_File_Close( VFS_Handle hFile )
{
	// Not initialized yet?
	if( !IsInit() )
	{
		SetLastError( VFS_ERROR_NOT_INITIALIZED_YET );
		return VFS_FALSE;
	}

	// Invalid Handle Value?
	if( hFile == VFS_INVALID_HANDLE_VALUE )
	{
		SetLastError( VFS_ERROR_INVALID_PARAMETER );
		return VFS_FALSE;
	}

	// Get the File Pointer.
	IFile* pFile = ( IFile* )( VFS_DWORD )hFile;

    // Invalid Handle Value?
	VFS_BOOL bFound = VFS_FALSE;
	for( FileMap::iterator iter = GetOpenFiles().begin(); iter != GetOpenFiles().end(); iter++ )
	{
		// Found?
		if( ( *iter ).second == pFile )
		{
			bFound = VFS_TRUE;
			break;
		}
	}
	if( !bFound )
	{
		SetLastError( VFS_ERROR_INVALID_PARAMETER );
		return VFS_FALSE;
	}

	// If the File will be deleted afterwards, remove the File from the
	// Open Files Map.
	if( pFile->GetRefCount() == 1 )
	{
		FileMap::iterator iter = GetOpenFiles().find( pFile->GetFileName() );
		if( iter == GetOpenFiles().end() )
		{
			SetLastError( VFS_ERROR_GENERIC );
			return VFS_FALSE;
		}
		GetOpenFiles().erase( iter );
	}

	// Release the File.
	pFile->Release();

	return VFS_TRUE;
}
bool ModifiedDateExclusionSubRule::matchWithoutNegate(const IFile& inputFile)
{
	if(!inputFile.isFile())
	{
		return false;
	}

	if(theOperator == OLDER_THAN)
		return inputFile.getLastModified() < timestamp;
	else
		return inputFile.getLastModified() > timestamp;
}
示例#12
0
bool
sTileset::Load(const char* filename, IFileSystem& fs)
{
  IFile* file = fs.Open(filename, IFileSystem::read);
  if (file == NULL)
    return false;

  bool result = LoadFromFile(file);

  file->Close();
  return result;
}
示例#13
0
//used by folders to lazily enumerate thier children as needed.
void VirtualFileSystemComponent::MapChildren( DefaultFolderImpl *parent, std::map<const wchar_t *, IFile *, WCharCmp> &children )
{
	_ASSERTE( parent );
	path path( parent->GetPhysicalPath() );
	_ASSERTE( is_directory( path ) );

	directory_iterator end_itr; // default construction yields past-the-end
	for ( directory_iterator itr( path ); itr != end_itr; ++itr ) {
		IFile *mappedChild = Map( ( *itr ).path(), parent );
		_ASSERTE( mappedChild );
		children.insert( std::pair<const wchar_t *, IFile *> ( mappedChild->GetName(), mappedChild ) );
	}
}
示例#14
0
bool
sTileset::Save(const char* filename, IFileSystem& fs) const
{
  // open the file
  IFile* file = fs.Open(filename, IFileSystem::write);
  if (file == NULL)
    return false;

  bool result = SaveToFile(file);

  file->Close();
  return result;
}
// writer thread gets a pointer to  orderbankwriter object
void * writer(void * args)
{
	
    thread_args *targ = (thread_args*) args;
     OrderedBlocks * obw = targ->obw;
	
    IFile* outbank = obw->_ref;
	
    int  * to_be_written =  &(obw->_to_be_written);
    std::vector< std::vector<u_int8_t> > * _buffWrite = &(obw->_buffWrite);
	
    
	
    //when waken, writes content of  vector  _buffWrite to bank
    while(1)
    {
        pthread_mutex_lock(&(obw->writer_mutex));
        while (obw->_buffer_full==0)
        {
            pthread_cond_wait(&(obw->buffer_full_cond), &(obw->writer_mutex));
        }
        obw->_writer_available = 0; //writer becomes busy
		  DEBUG((" **** writer thread  awaken !! ..  will write %i elems **** \n",*to_be_written));
        pthread_mutex_unlock(&(obw->writer_mutex));
        
		
        //writes the buffer

		
        for ( std::vector< std::vector<u_int8_t>  >::iterator it = _buffWrite->begin(); (it != _buffWrite->end()) && (*to_be_written) ; it++)
        {
            //outbank->insert((*it));
            //cout << "Size: " << (*it).size() << endl;
			outbank->fwrite( &(*it)[0] ,(*it).size(), 1);
            (*to_be_written) --;
        }
        
        
        //signal to others buffer has been written and writer is available again
        pthread_mutex_lock(&(obw->writer_mutex));
        obw->_buffer_full=0;
        obw->_writer_available=1;
		//  printf(" writer thread  setting  _buffer_full to 0 .. %i  tobewrit %i \n",obw->_buffer_full,*to_be_written);
        pthread_cond_broadcast(&(obw->writer_available_cond));
		DEBUG((" **** writer thread  finished !!            **** \n"));

        pthread_mutex_unlock(&(obw->writer_mutex));
    }
    
    
}
示例#16
0
bool
CConfigFile::Save(const char* filename, IFileSystem& fs) const
{
    IFile* file = fs.Open(filename, IFileSystem::write);
    if (file == NULL) {
        return false;
    }

    // find the section without a name and write that first
    std::map<std::string, Section>::const_iterator i;
    for (i = m_sections.begin(); i != m_sections.end(); i++) {
        if (i->first == "") {
            const Section& s = i->second;

            std::map<std::string, std::string>::const_iterator j;
            for (j = s.entries.begin(); j != s.entries.end(); j++) {
                write_string(file, j->first);
                file->Write("=", 1);
                write_string(file, j->second);
                file->Write("\n", 1);
            }

            file->Write("\n", 1);
        }
    }

    // write the rest of the sections
    for (i = m_sections.begin(); i != m_sections.end(); i++) {
        if (i->first != "") {
            file->Write("[", 1);
            write_string(file, i->first);
            file->Write("]\n", 2);

            const Section& s = i->second;
            std::map<std::string, std::string>::const_iterator j;
            for (j = s.entries.begin(); j != s.entries.end(); j++) {
                write_string(file, j->first);
                file->Write("=", 1);
                write_string(file, j->second);
                file->Write("\n", 1);
            }

            file->Write("\n", 1);

        }
    }

    file->Close();
    return true;
}
示例#17
0
int KSystemScriptTable::LuaLoadDataFromFile(Lua_State* L)
{
    int nRetCode = false;

    IFile *piFile = NULL;
    const char *pcszFile = NULL;
    const char *pcsBuff = NULL;
    size_t uBuffSize = 0;
    int nParamCount = 0;
    char szFilePath[MAX_PATH];

    KGLOG_PROCESS_ERROR(L);

    nRetCode = lua_gettop(L);
    KGLOG_PROCESS_ERROR(nRetCode == 1);

    pcszFile = lua_tostring(L, 1);
    KGLOG_PROCESS_ERROR(pcszFile);

    nRetCode = snprintf(
                   szFilePath,
                   sizeof(szFilePath),
                   "%s\\%s",
                   F_UI_USER_DATA_FOLDER,
                   pcszFile
               );
    KGLOG_PROCESS_ERROR(nRetCode > 0);
    szFilePath[sizeof(szFilePath) - 1] = '\0';
    FormatFilePath(szFilePath);

    nRetCode = KUiConfig::IsFilePathExist(szFilePath);
    KG_PROCESS_SUCCESS(!nRetCode);

    piFile = g_OpenFile(szFilePath, true);
    KGLOG_PROCESS_ERROR(piFile);

    uBuffSize = piFile->Size();
    KGLOG_PROCESS_ERROR(uBuffSize > 0);

    pcsBuff = (const char *)piFile->GetBuffer();
    KGLOG_PROCESS_ERROR(pcsBuff);

    lua_pushlstring(L, pcsBuff, uBuffSize);
    nParamCount++;

Exit1:
Exit0:
    SAFE_RELEASE(piFile);
    return nParamCount;
}
示例#18
0
void PlumedMain::readInputFile(std::string str) {
  plumed_assert(initialized);
  log.printf("FILE: %s\n",str.c_str());
  IFile ifile;
  ifile.link(*this);
  ifile.open(str);
  ifile.allowNoEOL();
  std::vector<std::string> words;
  while(Tools::getParsedLine(ifile,words) && words[0]!="ENDPLUMED") readInputWords(words);
  log.printf("END FILE: %s\n",str.c_str());
  log.flush();

  pilots=actionSet.select<ActionPilot*>();
}
示例#19
0
//-------------------------------------------------------------
// exports car model. Car models are typical MODEL structures
//-------------------------------------------------------------
void ExportCarModel(MODEL* model, int size, int index, const char* name_suffix)
{
	EqString model_name(varargs("%s/CARMODEL_%d_%s", g_levname_moddir.c_str(), index, name_suffix));

	// export model
	ExportDMODELToOBJ(model, model_name.c_str(), index, true);
			
	// save original dmodel2
	IFile* dFile = GetFileSystem()->Open(varargs("%s.dmodel",  model_name.c_str()), "wb", SP_ROOT);
	if(dFile)
	{
		dFile->Write(model, size, 1);
		GetFileSystem()->Close(dFile);
	}
}
示例#20
0
// Get the Reference Count (i.e. the Sum of the Reference Counts of all Open Files of this Archive).
VFS_DWORD CArchive::GetRefCount() const
{
	VFS_DWORD dwRefCount = 0;
	for( FileMap::iterator iter = GetOpenFiles().begin(); iter != GetOpenFiles().end(); iter++ )
	{
		IFile* pFile = ( *iter ).second;
		if( pFile->IsArchived() )
		{
			CArchiveFile* pArchiveFile = ( CArchiveFile* )pFile;
			if( pArchiveFile->GetArchive() == this )
				dwRefCount++;
		}
	}
	return dwRefCount;
}
示例#21
0
void ScriptComponent::Initialize()
{
    if (m_pFileName != nullptr)
    {
        IFile *pFile = MediaManager::Instance().FindMedia(m_pFileName, false);
        SetScriptFromBuffer(pFile->GetBuffer(), pFile->GetBufferLength());
        DELETE_AO pFile;

        //TODO crash
        //Game::Instance()->GetScriptEngine()->SetField(GetEntity(), "entity");

        //call function OnScriptInitialize()
        //Game::Instance()->GetScriptEngine()->CallFunction("OnScriptInitialize");
    }
}
示例#22
0
// Rename the specified File.
VFS_BOOL VFS_File_Rename( const VFS_String& strFrom, const VFS_String& strTo )				// pszTo has to be a single File Name without a Path.
{
	// Not initialized yet?
	if( !IsInit() )
	{
		SetLastError( VFS_ERROR_NOT_INITIALIZED_YET );
		return VFS_FALSE;
	}

	// Try to open the file to get the absolute file name and to see if the file is still open
	// and if it's not in an Archive (VFS_WRITE would fail otherwise).
	VFS_Handle hFile = VFS_File_Open( strFrom, VFS_READ | VFS_WRITE );
	if( hFile == VFS_INVALID_HANDLE_VALUE )
		return VFS_FALSE;

	// Get the File Pointer.
	IFile* pFile = ( IFile* )( VFS_DWORD )hFile;

	// Check if there are still references to the File (but count ourself).
	if( pFile->GetRefCount() > 1 )
	{
		// Close the File.
		VFS_File_Close( hFile );

        SetLastError( VFS_ERROR_IN_USE );
		return VFS_FALSE;
	}

	// Get the absolute File Name.
	VFS_String strAbsoluteFileName = pFile->GetFileName();

	// Close the File.
	VFS_File_Close( hFile );

	// Make the Target Name absolute.
	VFS_String strAbsoluteTo;
	VFS_Util_GetPath( strAbsoluteFileName, strAbsoluteTo );
	strAbsoluteTo = WithoutTrailingSeparator( strAbsoluteTo, VFS_TRUE ) + VFS_PATH_SEPARATOR + strTo;

	// Try to rename the File.
	if( !VFS_RENAME( strAbsoluteFileName, strAbsoluteTo ) )
	{
		SetLastError( VFS_ERROR_PERMISSION_DENIED );
		return VFS_FALSE;
	}

	return VFS_TRUE;
}
示例#23
0
//-------------------------------------------------------------
// exports model to single file
//-------------------------------------------------------------
void ExportDMODELToOBJ(MODEL* model, const char* model_name, int model_index, bool isCarModel = false)
{
	IFile* mdlFile = GetFileSystem()->Open(varargs("%s.obj", model_name), "wb", SP_ROOT);

	if(mdlFile)
	{
		Msg("----------\nModel %s (%d)\n", model_name, model_index);

		mdlFile->Print("mtllib MODELPAGES.mtl\r\n");

		WriteMODELToObjStream( mdlFile, model, model_index, true );

		// success
		GetFileSystem()->Close(mdlFile);
	}
}
示例#24
0
bool CoeffsBase::getIterationCounterAndTimeFromFile(IFile& ifile) {
  bool field_found=false;
  if(ifile.FieldExist(field_time_)) {
    field_found=true;
    double time_tmp;
    ifile.scanField(field_time_,time_tmp);
    time_md=time_tmp;
  }
  if(ifile.FieldExist(field_iteration_)) {
    field_found=true;
    int iter_tmp;
    ifile.scanField(field_iteration_,iter_tmp);
    iteration_opt=(unsigned int) iter_tmp;
  }
  return field_found;
}
示例#25
0
文件: main.cpp 项目: zhoumingzhe/vfs
int main(int argc, char* argv[])
{
    _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
    if(argc < 3)
    {
        printf("usage: %s directory package", argv[0]);
        return 0;
    }
    IFile::OpenMode mode = IFile::O_Write;
    if(!PathFileExistsA(argv[1]))
        mode = IFile::O_Truncate;
    IFile *pFile = OpenDiskFile(argv[1], mode);
    BlockManager* pMgr = new BlockManager(pFile, mode==IFile::O_Truncate, offset_type(1024));
    BlockFS *pFS = new BlockFS(pMgr, mode);
    std::vector<BlockFileEntry> vecEntries = pFS->GetEntries();
    std::map<std::string, MD5Index> mapEntries;
    for(std::vector<BlockFileEntry>::iterator it = vecEntries.begin();
        it != vecEntries.end(); ++it)
    {
        if(std::string("")!=it->name)
        {
            assert(mapEntries.find(it->name)==mapEntries.end());
            mapEntries[it->name] = it->index;
        }
    }
    std::vector<std::string> add;
    ScanFileRecursively(argv[2], pFS, mapEntries, add);

    for(std::map<std::string, MD5Index>::iterator it = mapEntries.begin(); it != mapEntries.end(); ++it)
        pFS->RemoveFile(it->first.c_str());

    for(std::vector<std::string>::iterator it = add.begin(); it != add.end(); ++it)
    {
        IFile* pTemp = OpenDiskFile(it->c_str(), IFile::O_ReadOnly);
        offset_type length = pTemp->GetSize();
        char* buff = new char[(size_t)length.offset];
        pTemp->Read(buff, length);
        printf("adding %s, %d bytes\n", it->c_str(), length);
        pFS->AddFile(it->c_str(), buff, length, length > pFS->GetBlockDataSize());
        delete[]buff;
        delete pTemp;
    }
    delete pFS;
    delete pMgr;
    delete pFile;
    return 0;
}
示例#26
0
	/*
	check that files inside enumeratoed archives can be read correctly
	*/
	TEST_FIXTURE( VFSTestFixture, ZipArchiveContentTests ) {
		_vfs->Mount( ( Resources::Instance().RootDir() + L"../../../tests/content/test.zip" ).c_str() );

		IFile *file = _vfs->GetFile( L"content/test.lua" );
		IFileReader *reader = nullptr;
		CHECK_EQUAL( MGDF_OK, file->Open( &reader ) );
		CHECK( reader != nullptr );

		std::vector<std::string> list;
		ReadLines( reader, list );

		//see if the file has as many lines as we expect
		CHECK_EQUAL( 20, list.size() );
		//check to see the first and last lines are as expected
		CHECK_EQUAL( "class 'ConsoleStorageListener'(MGDF.StorageListener)", list[0] );
		CHECK_EQUAL( "end", list[19] );
	}
示例#27
0
	/**
	check that files in the standard file can be read from the vfs correctly
	*/
	TEST_FIXTURE( VFSTestFixture, FileSystemContentTests ) {
		_vfs->Mount( ( Resources::Instance().RootDir() + L"../../../tests/content" ).c_str() );

		IFile *file = _vfs->GetFile( L"console.json" );
		IFileReader *reader = nullptr;
		CHECK_EQUAL( MGDF_OK, file->Open( &reader ) );
		CHECK( reader != nullptr );

		std::vector<std::string> list;
		ReadLines( reader, list );

		//see if the file has as many lines as we expect
		CHECK_EQUAL( 17, list.size() );
		//check to see the first and last lines are as expected
		CHECK_EQUAL( "{", list[0] );
		CHECK_EQUAL( "}", list[16] );
	}
示例#28
0
	void Texture::SaveTexture( const OutPutTextureData& saveto )
	{
		unsigned long i;
		png_structp png_ptr;
		png_infop info_ptr;
		png_colorp palette;
		png_byte *image;
		png_bytep *row_pointers;

		IFile* writefile = IOSystem::Instance().FileFactory(saveto.m_Path);
		writefile->OpenFile( IFile::AT_READ );


		png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		info_ptr = png_create_info_struct(png_ptr);
		png_set_write_fn( png_ptr, writefile, png_rw, png_flush );
		//png_init_io(png_ptr, writefile.BaseFile() );

		int colortype, bitesize;
		switch( saveto.m_Pixel )
		{
		case Device::PF_R8G8B8: colortype = PNG_COLOR_TYPE_RGB; bitesize = 3; break;
		case Device::PF_R8G8B8A8: colortype = PNG_COLOR_TYPE_RGBA; bitesize = 4; break;
		}
		png_set_IHDR(png_ptr, info_ptr, saveto.m_Size.m_x, saveto.m_Size.m_y, 8, colortype,
			PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
		palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color));
		png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);
		png_write_info(png_ptr, info_ptr);
		png_set_packing(png_ptr);
		row_pointers = (png_bytep *)malloc(saveto.m_Size.m_y * sizeof(png_bytep));

		for (i = 0; i < saveto.m_Size.m_y; i++)
		{
			row_pointers[i] = (png_bytep)&saveto.m_Data[i * saveto.m_Size.m_y * bitesize];
		}
		png_write_image(png_ptr, row_pointers);
		png_write_end(png_ptr, info_ptr);
		png_free(png_ptr, palette);
		palette = NULL;
		png_destroy_write_struct(&png_ptr, &info_ptr);
		free(row_pointers);
		row_pointers = NULL;
		writefile->CloseFile( );
		IOSystem::Instance().FileDestroy( writefile );
	}
示例#29
0
static VFS_Handle TryToOpen( const VFS_String& strFileName, VFS_DWORD dwFlags )
{
	// Absolute?
	if( VFS_Util_IsAbsoluteFileName( strFileName ) )
	{
		// Already open?
		if( GetOpenFiles().find( ToLower( strFileName ) ) != GetOpenFiles().end() )
		{
			IFile* pFile = GetOpenFiles()[ ToLower( strFileName ) ];
			pFile->Add();
			return ( VFS_Handle )( VFS_DWORD )pFile;
		}

		// Exists a Standard File?
		if( CStdIOFile::Exists( strFileName ) )
			return AddAndConvert( CStdIOFile::Open( strFileName, dwFlags ), strFileName );

		// Try to open an Archive File.
		return AddAndConvert( CArchiveFile::Open( strFileName, dwFlags ), strFileName );
	}

	// For each Root Path...
	for( VFS_RootPathList::iterator iter = GetRootPaths().begin(); iter != GetRootPaths().end(); iter++ )
	{
		VFS_String strAbsoluteFileName = ToLower( WithoutTrailingSeparator( *iter, VFS_TRUE ) + VFS_PATH_SEPARATOR + strFileName );

		// Already open?
		if( GetOpenFiles().find( strAbsoluteFileName ) != GetOpenFiles().end() )
		{
			IFile* pFile = GetOpenFiles()[ strAbsoluteFileName ];
			pFile->Add();
			return ( VFS_Handle )( VFS_DWORD )pFile;
		}

		// Exists a Standard File?
		if( CStdIOFile::Exists( strAbsoluteFileName ) )
			return AddAndConvert( CStdIOFile::Open( strAbsoluteFileName, dwFlags ), strAbsoluteFileName );

		// Try to open an Archive File.
		if( CArchiveFile::Exists( strAbsoluteFileName ) )
			return AddAndConvert( CArchiveFile::Open( strAbsoluteFileName, dwFlags ), strAbsoluteFileName );
	}

    SetLastError( VFS_ERROR_NOT_FOUND );
	return VFS_INVALID_HANDLE_VALUE;
}
示例#30
0
	IFile* open(const DeviceList& device_list, const Path& file, Mode mode) override
	{
		IFile* prev = createFile(device_list);

		if (prev)
		{
			if (prev->open(file, mode))
			{
				return prev;
			}
			else
			{
				prev->release();
				return nullptr;
			}
		}
		return nullptr;
	}