Esempio n. 1
0
        bool serveFile(const string& URI, string& contentType, string& content) const {
            if (URI.length() == 0) return false;
            
            string filename = BASE_DIR + URI;
            if (URI[URI.length() - 1] == '/') filename += DEFAULT_FILE;

            LogDebug("read file: %s", filename.c_str());

            auto deleter = [](FILE *p) {fclose(p); };
            unique_ptr<FILE, decltype(deleter)> pFile(fopen(filename.c_str(), "r"), deleter);
            if (pFile == nullptr) return false;
            
            contentType = getContentType(getFileSuffix(filename));
            
            content.clear();
            char buff[READ_FILE_BUFFER_SIZE];

            fgets(buff, READ_FILE_BUFFER_SIZE - 1, pFile.get());
            while (! feof(pFile.get())) {
                content += buff;
                fgets(buff, READ_FILE_BUFFER_SIZE - 1, pFile.get());
            }

            return true;
        }
Esempio n. 2
0
MemoryCard::MemoryCard(const std::string& filename, int _card_index, u16 sizeMb)
	: MemoryCardBase(_card_index, sizeMb)
	, m_filename(filename)
{
	File::IOFile pFile(m_filename, "rb");
	if (pFile)
	{
		// Measure size of the existing memcard file.
		memory_card_size = (u32)pFile.GetSize();
		nintendo_card_id = memory_card_size / SIZE_TO_Mb;
		m_memcard_data = std::make_unique<u8[]>(memory_card_size);
		memset(&m_memcard_data[0], 0xFF, memory_card_size);

		INFO_LOG(EXPANSIONINTERFACE, "Reading memory card %s", m_filename.c_str());
		pFile.ReadBytes(&m_memcard_data[0], memory_card_size);
	}
	else
	{
		// Create a new 128Mb memcard
		nintendo_card_id = sizeMb;
		memory_card_size = sizeMb * SIZE_TO_Mb;

		m_memcard_data = std::make_unique<u8[]>(memory_card_size);
		// Fills in MC_HDR_SIZE bytes
		GCMemcard::Format(&m_memcard_data[0], m_filename.find(".JAP.raw") != std::string::npos, sizeMb);
		memset(&m_memcard_data[MC_HDR_SIZE], 0xFF, memory_card_size - MC_HDR_SIZE);

		INFO_LOG(EXPANSIONINTERFACE, "No memory card found. A new one was created instead.");
	}

	// Class members (including inherited ones) have now been initialized, so
	// it's safe to startup the flush thread (which reads them).
	m_flush_buffer = std::make_unique<u8[]>(memory_card_size);
	m_flush_thread = std::thread(&MemoryCard::FlushThread, this);
}
Esempio n. 3
0
int main(int argc, char * argv[])
{
	if (argc != 2)
	{
		cerr<<"No File Name";
		exit(1);
	}
	ifstream pFile(argv[1],ios_base::in);
	if(!pFile.is_open())
	{
		cerr<<"No such File";
		exit(1);
	}

    string outputFile;
    outputFile.append(argv[1]);
    outputFile = outputFile.substr(0,outputFile.size()-3);
    outputFile.append(".lextext");
	Scaner scan(pFile);
    scan.Scan(outputFile);
    cout<<"输出文件:"<<outputFile<<endl;

    Parse parse(scan);

    Node* parseTree = parse.program();

#ifdef _DEBUG
    parse.printTree( parseTree );
#endif
    cout<<"按下任何键继续..."<<endl;
    cin.get();
    return 0;
}
std::vector<std::string> readarray(std::string filename,const std::string delims=",;: \t"){
  ///@param filename The name of the file to open.
  ///@param delims A string of delimeters to split by.
  std::vector<std::string> tokens;

  const int SIZE = MAX_ELEMS_PER_LINE;
  char *buffer = new char[SIZE];
  std::ifstream pFile (filename.c_str(),std::ios::in);
  
  if(!pFile){
    fileError(filename);
    exit(0);
  }
  
  std::string tmp_string;
  //we are reading an array, so just keep reading until no more lines
  while(!pFile.eof()){
    pFile.getline(buffer,SIZE);
    tmp_string = std::string(buffer);
    get_lexemes(tmp_string,tokens,delims);
    
  }
  pFile.close();
  delete [] buffer;
  ///now we have a token array of string coerce the types now
  //typecast_stringarray(tokens);
  return tokens;
}
Esempio n. 5
0
bool TERRAIN::LoadHeightMap(const QString& filename, int size)
{
  if( heightMap.arrayHeightMap )
    UnloadHeightMap( );

  QFile pFile(filename);
#if QT_VERSION >= 0x040000
	if (!pFile.open(QIODevice::ReadOnly))
#else
	if (!pFile.open(IO_ReadOnly))
#endif
    return false;

  heightMap.arrayHeightMap = new unsigned char [size*size];

  if( heightMap.arrayHeightMap==NULL )
    return false;

  //lire la carte d'hauteurs, format RAW
  QDataStream in(&pFile);
  for (int i=0; i<sizeHeightMap*sizeHeightMap; i++)
    in >> heightMap.arrayHeightMap[i];
  
  pFile.close();

  sizeHeightMap = size;

  return true;
}
void CBaseTopPane::CopyBackgroundPresetToForeground()
{
	// Create new background set
	IChunkFileMemory* pPresetBackgroundNew = IChunkFileMemory::Create();
	tint32 iVersionNumber = 1;
	pPresetBackgroundNew->Open(IFile::FileCreate, iVersionNumber);

	// Read current preset into background preset set
	mpGUI->OnSavePreset(dynamic_cast<IChunkFile*>(pPresetBackgroundNew));

	// Get the memory from the current background set
	tint64 iMemSize = mpPresetBackground->GetMemorySize();
	void* pMem = (void*)new char[(tuint)iMemSize];
	mpPresetBackground->GetMemory(pMem);

	// Delete the current background set
	mpPresetBackground->Destroy();

	// Switch, so the current preset is the new background
	mpPresetBackground = pPresetBackgroundNew;

	// Create chunk with old background
	CAutoDelete<IChunkFileMemory> pFile(IChunkFileMemory::Create());
	pFile->Open(IFile::FileRead, iVersionNumber, pMem, iMemSize);

	// Set the preset
	mpGUI->OnLoadPreset(pFile);

	// Delete the memory
	delete[] pMem;
}
Esempio n. 7
0
void CLibraryMaps::Serialize2(CArchive& ar, int nVersion)
{
	if ( nVersion < 18 ) return;

	if ( ar.IsStoring() )
	{
		ar.WriteCount( m_pDeleted.GetCount() );

		for ( POSITION pos = m_pDeleted.GetHeadPosition() ; pos ; )
		{
			m_pDeleted.GetNext( pos )->Serialize( ar, nVersion );
		}
	}
	else // Loading
	{
		for ( DWORD_PTR nCount = ar.ReadCount() ; nCount > 0 ; nCount-- )
		{
			//CLibraryFile* pFile = new CLibraryFile( NULL );
			CAutoPtr< CLibraryFile > pFile( new CLibraryFile( NULL ) );
			if ( ! pFile )
				AfxThrowMemoryException();

			pFile->Serialize( ar, nVersion );

			if ( ! LibraryMaps.LookupFileByHash( pFile ) )
				Library.AddFile( pFile.Detach() );
		}
	}
}
Esempio n. 8
0
static bool LoadRom(const std::string& fname, int size_in_words, u16 *rom)
{
	File::IOFile pFile(fname, "rb");
	const size_t size_in_bytes = size_in_words * sizeof(u16);
	if (pFile)
	{
		pFile.ReadArray(rom, size_in_words);
		pFile.Close();

		// Byteswap the rom.
		for (int i = 0; i < size_in_words; i++)
			rom[i] = Common::swap16(rom[i]);

		// Always keep ROMs write protected.
		WriteProtectMemory(rom, size_in_bytes, false);
		return true;
	}

	PanicAlertT(
		"Failed to load DSP ROM:\t%s\n"
		"\n"
		"This file is required to use DSP LLE.\n"
		"It is not included with Dolphin as it contains copyrighted data.\n"
		"Use DSPSpy to dump the file from your physical console.\n"
		"\n"
		"You may use the DSP HLE engine which does not require ROM dumps.\n"
		"(Choose it from the \"Audio\" tab of the configuration dialog.)", fname.c_str());
	return false;
}
Esempio n. 9
0
//==================================================
//! Load a file from the VFS into memory, can throw a FileIOException
//==================================================
void System::VFS::LoadRaw( const string& strFilename, vector<byte>& data ) {
	// Check to see if it exists
	if( !PHYSFS_exists(strFilename.c_str()) ) {
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}
	
	// Open the file
	shared_ptr<PHYSFS_file> pFile( PHYSFS_openRead(strFilename.c_str()), PHYSFS_close );
	if( pFile.get() == NULL ) {
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}

	// Try to read the number of bytes, fail if we can't
	PHYSFS_sint64 nBytes= PHYSFS_fileLength( pFile.get() );
	if( nBytes < 0 ) {
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}
	data.resize( unsigned(nBytes) );

	// Try to read the data
	PHYSFS_sint64 nBytesRead= PHYSFS_read( pFile.get(), &data[0], sizeof(byte), data.size() );
	// Check for unexpected length
	if( nBytesRead != nBytes ) {
		data.resize( unsigned(nBytesRead) );
		THROW_EXCEPTION( FileReadException() << FileIOExceptionFilename(strFilename) );
	}
}
void CBaseTopPane::ActionLoad()
{
	// Get the directory
	std::string sPresetDirectory = mpGUI->GetPresetFolder();
	
	// Get product name
	tchar pszProductName[128];
	GetPlugIn()->GetProductName(pszProductName);

	// Create the dialog
	CAutoDelete<ge::IOpenDialog> pDialog(ge::IOpenDialog::Create());

	// Open dialog
	tchar pszPathName[512];
	pDialog->DoDialog((tchar*)pszPathName,
		(tchar*)(sPresetDirectory.c_str()),
		(tchar*)"*.preset",
		(tchar*)(std::string(pszProductName) + " Presets (*.preset)").c_str());

	if (pszPathName[0] == 0) {
		// Error in dialog, or user pressed cancel
		return;
	}

	msPresetPathName = std::string((char*)pszPathName);

	CAutoDelete<IChunkFile> pFile(IChunkFile::Create());
	tint32 iVersionNumber;
	if (pFile->Open((const tchar*)(msPresetPathName.c_str()),
		IFile::FileRead,
		iVersionNumber)) {
		mpGUI->OnLoadPreset(pFile);
	}
}
Esempio n. 11
0
void innerFlush(FlushData* data)
{
	File::IOFile pFile(data->filename, "wb");
	if (!pFile)
	{
		std::string dir;
		SplitPath(data->filename, &dir, 0, 0);
		if (!File::IsDirectory(dir))
			File::CreateFullPath(dir);
		pFile.Open(data->filename, "wb");
	}

	if (!pFile) // Note - pFile changed inside above if
	{
		PanicAlertT("Could not write memory card file %s.\n\n"
			"Are you running Dolphin from a CD/DVD, or is the save file maybe write protected?", data->filename.c_str());
		return;
	}

	pFile.WriteBytes(data->memcardContent, data->memcardSize);

	if (!data->bExiting)
		Core::DisplayMessage(StringFromFormat("Wrote memory card %c contents to %s",
			data->memcardIndex ? 'B' : 'A', data->filename.c_str()).c_str(), 4000);
	return;
}
Esempio n. 12
0
HBITMAP CSkin::LoadBitmap(CString& strName)
{
	int nPos = strName.Find( '$' );

	if ( nPos < 0 )
	{
		CImageFile pFile(strName );
		return CImageFile::LoadBitmap(strName);
	}
	else
	{
		HINSTANCE hInstance = NULL;
		UINT nID = 0;
		
		if ( _stscanf( strName.Left( nPos ), _T("%lu"), &hInstance ) != 1 ) return NULL;
		if ( _stscanf( strName.Mid( nPos + 1 ), _T("%lu"), &nID ) != 1 ) return NULL;

		if ( LPCTSTR pszType = _tcsrchr( strName, '.' ) )
		{
			pszType ++;
			CImageFile::LoadBitmap( hInstance, nID, pszType );
		}
		else
		{
			return (HBITMAP)LoadImage( hInstance, MAKEINTRESOURCE(nID), IMAGE_BITMAP, 0, 0, 0 );
		}
	}
	return NULL;
}
Esempio n. 13
0
// M-- modify the read of point
void RTreeIndex::CreateRTree()
{
	diskfile = StorageManager::createNewDiskStorageManager(treeFile, rtreePageSize);		//4k size page
	file = StorageManager::createNewRandomEvictionsBuffer(*diskfile, cacheblock, false);		//cache block number 1000
	tree = RTree::createNewRTree(*file, 0.7, capacity, capacity, 2, SpatialIndex::RTree::RV_RSTAR, indexIdentifier);

	ifstream pFile(pointFile.c_str());
	if (pFile.is_open())
	{		
		int count = 0;
		while (! pFile.eof() )
		{
			string line;
			getline(pFile, line);
			if(line == "")
				continue;
			int id;char c;
			double coor[2];
			istringstream iss(line);
			// M--
			//iss>> id >>c>>coor[0]>>c>>coor[1];
			iss >> id >> coor[0] >> coor[1];
			Point p = Point(coor, 2);			
			tree->insertData(0, 0, p, count);
			count++;
		}
		pFile.close();		
	}
Esempio n. 14
0
void CSchedulerWnd::OnSchedulerActivate()
{
	HRESULT hr;

	CString sTaskName = GetItem( m_wndList.GetNextItem( -1, LVIS_SELECTED ) );
	if ( sTaskName.IsEmpty() )
		return;

	CComPtr< ITask > pTask;
	hr = m_pScheduler->Activate( sTaskName, IID_ITask, (IUnknown**)&pTask );
	if ( FAILED( hr ) )
		return;

	DWORD nFlags = 0;
	hr = pTask->GetFlags( &nFlags );
	if ( ( nFlags & TASK_FLAG_DISABLED ) == TASK_FLAG_DISABLED )
	{
		hr = pTask->SetFlags( nFlags & ~TASK_FLAG_DISABLED );
		if ( SUCCEEDED( hr ) )
		{
			CComQIPtr< IPersistFile > pFile( pTask );
			if ( pFile )
			{
				hr = pFile->Save( NULL, TRUE );
				if ( SUCCEEDED( hr ) )
				{
					Update();
				}
			}
		}
	}
}
CEXIMemoryCard::CEXIMemoryCard(const int index)
	: card_index(index)
	, m_bDirty(false)
{
	m_strFilename = (card_index == 0) ? SConfig::GetInstance().m_strMemoryCardA : SConfig::GetInstance().m_strMemoryCardB;
	if (Movie::IsPlayingInput() && Movie::IsConfigSaved() && Movie::IsUsingMemcard() && Movie::IsStartingFromClearSave())
		m_strFilename = File::GetUserPath(D_GCUSER_IDX) + "Movie.raw";

	// we're potentially leaking events here, since there's no UnregisterEvent until emu shutdown, but I guess it's inconsequential
	et_this_card = CoreTiming::RegisterEvent((card_index == 0) ? "memcardFlushA" : "memcardFlushB", FlushCallback);
	et_cmd_done = CoreTiming::RegisterEvent((card_index == 0) ? "memcardDoneA" : "memcardDoneB", CmdDoneCallback);

	interruptSwitch = 0;
	m_bInterruptSet = 0;
	command = 0;
	status = MC_STATUS_BUSY | MC_STATUS_UNLOCKED | MC_STATUS_READY;
	m_uPosition = 0;
	memset(programming_buffer, 0, sizeof(programming_buffer));
	formatDelay = 0;

	//Nintendo Memory Card EXI IDs
	//0x00000004 Memory Card 59		4Mbit
	//0x00000008 Memory Card 123	8Mb
	//0x00000010 Memory Card 251	16Mb
	//0x00000020 Memory Card 507	32Mb
	//0x00000040 Memory Card 1019	64Mb
	//0x00000080 Memory Card 2043	128Mb

	//0x00000510 16Mb "bigben" card
	//card_id = 0xc243;

	card_id = 0xc221; // It's a Nintendo brand memcard

	File::IOFile pFile(m_strFilename, "rb");
	if (pFile)
	{
		// Measure size of the memcard file.
		memory_card_size = (int)pFile.GetSize();
		nintendo_card_id = memory_card_size / SIZE_TO_Mb;
		memory_card_content = new u8[memory_card_size];
		memset(memory_card_content, 0xFF, memory_card_size);

		INFO_LOG(EXPANSIONINTERFACE, "Reading memory card %s", m_strFilename.c_str());
		pFile.ReadBytes(memory_card_content, memory_card_size);

	}
	else
	{
		// Create a new 128Mb memcard
		nintendo_card_id = 0x00000080;
		memory_card_size = nintendo_card_id * SIZE_TO_Mb;

		memory_card_content = new u8[memory_card_size];
		GCMemcard::Format(memory_card_content, m_strFilename.find(".JAP.raw") != std::string::npos, nintendo_card_id);
		memset(memory_card_content+MC_HDR_SIZE, 0xFF, memory_card_size-MC_HDR_SIZE);
		WARN_LOG(EXPANSIONINTERFACE, "No memory card found. Will create a new one.");
	}
	SetCardFlashID(memory_card_content, card_index);
}
Esempio n. 16
0
bool DotWriter::SendToDotAppOutputDirectory(const wxString& dot_fn)
{ // (re)write dot.txt file
    wxFile pFile(dot_fn, wxFile::write);

    bool ok = pFile.Write(m_OutputString);

    return ok;
}
Esempio n. 17
0
CEXIMemoryCard::CEXIMemoryCard(const std::string& _rName, const std::string& _rFilename, int _card_index) :
	m_strFilename(_rFilename),
	card_index(_card_index),
	m_bDirty(false)
{
	cards[_card_index] = this;
	et_this_card = CoreTiming::RegisterEvent(_rName.c_str(), FlushCallback);
	reloadOnState = SConfig::GetInstance().b_reloadMCOnState;
 
	interruptSwitch = 0;
	m_bInterruptSet = 0;
	command = 0;
	status = MC_STATUS_BUSY | MC_STATUS_UNLOCKED | MC_STATUS_READY;
	m_uPosition = 0;
	memset(programming_buffer, 0, sizeof(programming_buffer));
	formatDelay = 0;
 
	//Nintendo Memory Card EXI IDs
	//0x00000004 Memory Card 59		4Mbit
	//0x00000008 Memory Card 123	8Mb
	//0x00000010 Memory Card 251	16Mb
	//0x00000020 Memory Card 507	32Mb
	//0x00000040 Memory Card 1019	64Mb
	//0x00000080 Memory Card 2043	128Mb
 
	//0x00000510 16Mb "bigben" card
	//card_id = 0xc243;
 
	card_id = 0xc221; // It's a nintendo brand memcard
 
	File::IOFile pFile(m_strFilename, "rb");
	if (pFile)
	{
		// Measure size of the memcard file.
		memory_card_size = (int)pFile.GetSize();
		nintendo_card_id = memory_card_size / SIZE_TO_Mb;
		memory_card_content = new u8[memory_card_size];
		memset(memory_card_content, 0xFF, memory_card_size);
 
		INFO_LOG(EXPANSIONINTERFACE, "Reading memory card %s", m_strFilename.c_str());
		pFile.ReadBytes(memory_card_content, memory_card_size);
		SetCardFlashID(memory_card_content, card_index);

	}
	else
	{
		// Create a new 128Mb memcard
		nintendo_card_id = 0x00000080;
		memory_card_size = nintendo_card_id * SIZE_TO_Mb;

		memory_card_content = new u8[memory_card_size];
		memset(memory_card_content, 0xFF, memory_card_size);
 
		WARN_LOG(EXPANSIONINTERFACE, "No memory card found. Will create new.");
		Flush();
	}
}
Esempio n. 18
0
void ObjModel::loadMaterialFile( std::string fileName, std::string dirName )
{
	std::ifstream pFile(fileName.c_str());
	if (!pFile.is_open())
	{
		std::cout << "Could not open file " << fileName << std::endl;
		return;
	}

	MaterialInfo* currentMaterial = NULL;

	while(!pFile.eof())
	{
		std::string line;
		std::getline(pFile, line);

		line = replace(line, "\t", " ");
		line = replace(line, "\r", " ");
		while(line.find("  ") != std::string::npos)
			line = replace(line, "  ", " ");
		if(line == "")
			continue;
		if(line[0] == ' ')
			line = line.substr(1);
		if(line == "")
			continue;
		if(line[line.length()-1] == ' ')
			line = line.substr(0, line.length()-1);
		if(line == "")
			continue;
		if(line[0] == '#')
			continue;

		std::vector<std::string> params = split(line, " ");
		params[0] = toLower(params[0]);

		if(params[0] == "newmtl")
		{
			if(currentMaterial != NULL)
			{
				materials.push_back(currentMaterial);
			}
			currentMaterial = new MaterialInfo();
			currentMaterial->name = params[1];
		}
		else if(params[0] == "map_kd")
		{
			currentMaterial->hasTexture = true;
			currentMaterial->texture = new Texture(dirName + "/" + params[1]);
		}
		else
			std::cout<<"Didn't parse "<<params[0]<<" in material file"<<std::endl;
	}
	if(currentMaterial != NULL)
		materials.push_back(currentMaterial);

}
Esempio n. 19
0
CChunkFileReader::Error CChunkFileReader::SaveFile(const std::string& _rFilename, int _Revision, const char *_VersionString, u8 *buffer, size_t sz) {
    INFO_LOG(COMMON, "ChunkReader: Writing %s" , _rFilename.c_str());

    File::IOFile pFile(_rFilename, "wb");
    if (!pFile)
    {
        ERROR_LOG(COMMON, "ChunkReader: Error opening file for write");
        return ERROR_BAD_FILE;
    }

    bool compress = true;

    // Create header
    SChunkHeader header;
    header.Compress = compress ? 1 : 0;
    header.Revision = _Revision;
    header.ExpectedSize = (u32)sz;
    header.UncompressedSize = (u32)sz;
    strncpy(header.GitVersion, _VersionString, 32);
    header.GitVersion[31] = '\0';

    // Write to file
    if (compress) {
        size_t comp_len = snappy_max_compressed_length(sz);
        u8 *compressed_buffer = new u8[comp_len];
        snappy_compress((const char *)buffer, sz, (char *)compressed_buffer, &comp_len);
        delete [] buffer;
        header.ExpectedSize = (u32)comp_len;
        if (!pFile.WriteArray(&header, 1))
        {
            ERROR_LOG(COMMON, "ChunkReader: Failed writing header");
            return ERROR_BAD_FILE;
        }
        if (!pFile.WriteBytes(&compressed_buffer[0], comp_len)) {
            ERROR_LOG(COMMON, "ChunkReader: Failed writing compressed data");
            return ERROR_BAD_FILE;
        }	else {
            INFO_LOG(COMMON, "Savestate: Compressed %i bytes into %i", (int)sz, (int)comp_len);
        }
        delete [] compressed_buffer;
    } else {
        if (!pFile.WriteArray(&header, 1))
        {
            ERROR_LOG(COMMON, "ChunkReader: Failed writing header");
            return ERROR_BAD_FILE;
        }
        if (!pFile.WriteBytes(&buffer[0], sz))
        {
            ERROR_LOG(COMMON, "ChunkReader: Failed writing data");
            return ERROR_BAD_FILE;
        }
        delete [] buffer;
    }

    INFO_LOG(COMMON, "ChunkReader: Done writing %s",  _rFilename.c_str());
    return ERROR_NONE;
}
void CPocoLoggerTester::test_SplitterLogger()
{
    Poco::AutoPtr<Poco::ConsoleChannel> pCons(new Poco::ConsoleChannel);  
    Poco::AutoPtr<Poco::SimpleFileChannel> pFile(new Poco::SimpleFileChannel("test.log"));  
    Poco::AutoPtr<Poco::SplitterChannel> pSplitter(new Poco::SplitterChannel);  
    pSplitter->addChannel(pCons);  
    pSplitter->addChannel(pFile);  
    Poco::Logger::root().setChannel(pSplitter);  
    Poco::Logger::root().information("This is a test");
}
Esempio n. 21
0
CChunkFileReader::Error CChunkFileReader::GetFileTitle(const std::string &filename, std::string *title) {
	if (!File::Exists(filename)) {
		ERROR_LOG(COMMON, "ChunkReader: File doesn't exist");
		return ERROR_BAD_FILE;
	}

	File::IOFile pFile(filename, "rb");
	SChunkHeader header;
	return LoadFileHeader(pFile, header, title);
}
Esempio n. 22
0
iMatrix *readmatrix(std::string filename,const std::string delim=",;: \t"){
  ///@param filename A filename to read.@param delim A string of delimiters.
  std::vector<std::string> tokens;

  const int SIZE=500000;
  char buffer[SIZE];
 
  std::ifstream pFile (filename.c_str(),std::ios::in);
 
  
  if(!pFile){
    std::cout <<"Problems opening file" <<filename<<std::endl;
    exit(0);
  }

  
  std::string tmp_string;
  int doFirstRow =1;
  int itemsInFirstRow=0;
  int numRows =0;
  while(!pFile.eof()){
    pFile.getline(buffer,SIZE);
    tmp_string = std::string(buffer);
    
    if(doFirstRow){
      //if file has a emptystart line
      itemsInFirstRow = get_lexemes(tmp_string,tokens,delim);
      
      if (itemsInFirstRow==0)
	continue;
      // printf("items in first rwo:%d\n",itemsInFirstRow);
      doFirstRow=0;
      numRows++;
    }
    else{
      int nItems = get_lexemes(tmp_string,tokens,delim);
	//if line is empty
	if(nItems==0)
	  continue;
	numRows++;
	if(nItems!=itemsInFirstRow){
	  printf("row length mismatch at line:%d numitems is:%d shouldn't be:%d\t will exit\n",numRows,itemsInFirstRow,nItems);
	  exit(0);
	}
      }
  }

  iMatrix *data_ = allocIntMatrix(numRows,itemsInFirstRow);
  //now we have a token array of string coerce the types now
  typecast_stringarray_to_int_matrix(tokens,data_);
  //copy(tokens.begin(), tokens.end(), ostream_iterator<string>(cout, ", "));
  
  printf("\t-> Dimension of genotype datafile is (%d,%d)\n",data_->x,data_->y);
  return data_; 
}
iMatrix *readmatrix_filty_memory(std::string filename,const std::string delim=",;: \t"){
  ///@param filename A filename to read.@param delim A string of delimiters.
  std::vector<std::string> tokens;

  const int SIZE = MAX_ELEMS_PER_LINE;//defined in conf.h
  char buffer[SIZE];
 
  std::ifstream pFile (filename.c_str(),std::ios::in);
 
  
  if(!pFile){
    fileError(filename);
    exit(0);
  }

  
  std::string tmp_string;
  int doFirstRow =1;
  int itemsInFirstRow=0;
  int numRows =0;
  while(!pFile.eof()){
     pFile.getline(buffer,SIZE);
    tmp_string = std::string(buffer);
    if(doFirstRow){
      //if file has a emptystart line
      itemsInFirstRow = get_lexemes(tmp_string,tokens,delim);
      
      if (itemsInFirstRow==0)
	continue;
      // printf("items in first rwo:%d\n",itemsInFirstRow);
      doFirstRow=0;
      numRows++;
    }
    else{
      int nItems = get_lexemes(tmp_string,tokens,delim);
	//if line is empty
	if(nItems==0)
	  continue;
	numRows++;
	if(nItems!=itemsInFirstRow){
	  printf("row length mismatch at line:%d numitems is:%d shouldn't be:%d\t will exit\n",numRows,itemsInFirstRow,nItems);
	  exit(0);
	}
      }
  }
  flush_print("\r\t-> File has been read in now, will now typecheck...                              ");
  iMatrix *data_ = allocIntMatrix(numRows,itemsInFirstRow);
  //now we have a token array of string coerce the types now
  typecast_stringarray_to_int_matrix(tokens,data_);
  //copy(tokens.begin(), tokens.end(), ostream_iterator<string>(cout, ", "));
  return data_; 
}
Esempio n. 24
0
bool cell_library::read_cc_file(const string file_path) {
	ifstream pFile(file_path.c_str());
	stringstream buffer;
	if (!pFile.is_open()) {
		cerr << "ERROR: failed to open file " + file_path + "\n";
		return false;
	}

	cout << "INFO: successed to open file " + file_path + "\n";
	buffer << pFile.rdbuf();
	pFile.close();
	return parse_cc_file(buffer);
}
Esempio n. 25
0
/**
 * @brief MainWindow::saveLibToFile speichert die Datenbank in .csv Dateien
 */
void MainWindow::saveLibToFile(){
    QFile lendFile("lendlibLend.csv");
    QFile mFile("lendlibMedia.csv");
    QFile pFile("lendlibPerson.csv");
    /// Schreibe alle Personen
    if (lendFile.open(QFile::WriteOnly|QFile::Truncate)){
        QTextStream stream(&lendFile);
        QHash<int,int> lendList = lendlib->getLendList();
        QHash<int,int>::iterator i;
        stream << "Medium \t Ausgeliehen an\n";
        for(i = lendList.begin(); i != lendList.end(); ++i){
            stream << i.key() << "\t" << i.value() << "\n";
        }
        lendFile.close();
    }
    /// Schreibe alle Medien
    if (mFile.open(QFile::WriteOnly|QFile::Truncate)){
        QTextStream stream(&mFile);
        QMap<int,Medium*> mList = lendlib->getMList();
        stream << "ID \t Typ \t Titel\n";
        for(auto m: mList.keys()){
            QString mDetail;
            switch (mList.value(m)->getType()){
            case book:
                mDetail = ((Book*)mList.value(m))->getAuthor();
                break;
            case cd:
                mDetail = ((CD*)mList.value(m))->getInterpret();
                break;
            case dvd:
                mDetail = ((DVD*)mList.value(m))->getDirector();
                break;
            default:
                mDetail = "";
            }
            stream << mList.value(m)->getID() << "\t" << mList.value(m)->getType() << "\t" << mList.value(m)->getTitle() << "\t" << mDetail << "\n";
        }
        mFile.close();
    }
    /// Schreibe alle Ausleih-Relationen
    if (pFile.open(QFile::WriteOnly|QFile::Truncate)){
        QTextStream stream(&pFile);
        QMap<int,Person*> pList = lendlib->getPList();
        stream << "ID \t Name\n";
        for(auto p: pList.keys()){
            stream << pList.value(p)->getID()<< "\t" << pList.value(p)->getFullName() << "\n";
        }
        pFile.close();
    }
}
Esempio n. 26
0
void CSharedContent::UpdateLocation()
{
	m_Elements.clear();
	m_lastID = 0;
	m_contentMap = StringFromFormat("%sshared1/content.map", File::GetUserPath(D_WIIUSER_IDX).c_str());

	File::IOFile pFile(m_contentMap, "rb");
	SElement Element;
	while (pFile.ReadArray(&Element, 1))
	{
		m_Elements.push_back(Element);
		m_lastID++;
	}
}
Esempio n. 27
0
void ProfilerDump(u64 count)
{
	File::IOFile pFile("DSP_Prof.txt", "wt");
	if (pFile)
	{
		fprintf(pFile.GetHandle(), "Number of DSP steps: %" PRIu64 "\n\n", count);
		for (int i=0; i<PROFILE_MAP_SIZE;i++)
		{
			if (g_profileMap[i] > 0)
			{
				fprintf(pFile.GetHandle(), "0x%04X: %" PRIu64 "\n", i, g_profileMap[i]);
			}
		}
	}
}
int numberOfLines(const char *filename){
  const int SIZE=500000;
  char buffer[SIZE];
  int numLines=0;
  std::ifstream pFile (filename,std::ios::in);
  
  if(!pFile){
fileError(filename);
    return 0;
  }
  while(!pFile.eof()){
    pFile.getline(buffer,SIZE);
    numLines++;
  }
  return numLines;
}
Esempio n. 29
0
Module::HResult CINIFileAdapterFactory::GetAdapter(Module::IUnknown *object, const Module::GUID &iid, void **ppAdapter)
{
    if(iid != uuid_of(IINIFileAdapter))
        return SF_E_NOINTERFACE;

    Module::com_ptr<IFile> pFile(object);

    if(!pFile)
        return SF_E_INVALIDARG;

    CINIFileAdapter *pAdapter;
    create_instance_impl<CINIFileAdapter>(&pAdapter);
    pAdapter->FinalConstruct(pFile);

    *ppAdapter = static_cast<IINIFileAdapter*>(pAdapter);
    return SF_S_OK;
}
Esempio n. 30
0
// TODO make this useful :p
bool DumpCWCode(u32 _Address, u32 _Length)
{
	std::string filename = File::GetUserPath(D_DUMPDSP_IDX) + "DSP_UCode.bin";
	File::IOFile pFile(filename, "wb");

	if (pFile)
	{
		for (size_t i = _Address; i != _Address + _Length; ++i)
		{
			u16 val = g_dsp.iram[i];
			fprintf(pFile.GetHandle(), "    cw 0x%04x \n", val);
		}
		return true;
	}

	return false;
}