const bool ReadFromFile(const char* fileName, MGragh<int> &gragh){
  std::ifstream fileIn(fileName);
  if(!fileIn.is_open()){
    std::cout << "Can't open file " << fileName << std::endl;
    return false;
  }
  int maxNumber;
  int path;
  char buffer[1024];
  fileIn.getline(buffer, 1024);
  maxNumber = atoi(buffer);
  fileIn.getline(buffer, 1024);
  path = atoi(buffer);
  gragh.Clear();
  gragh.ResetSize(maxNumber);
  for(int i = 0; i < path; ++i){
    int beginNode;
    int endNode;
    fileIn >> beginNode;
    fileIn >> endNode;
    fileIn.getline(buffer, 1024);
    gragh.AddNodeAndEdge(beginNode, endNode);
  }
  
  return true;
}
// Function for handling reading in subsequent frames
size_t
VideoEncoder::ReadNextFrame()
{
    size_t bytes_read = fread(m_pVideoFrame, 1, m_nVideoFrameSize, fileIn());

    if (!feof(fileIn()))
    {
        if (bytes_read != m_nVideoFrameSize)
        {
            printf("ReadNextFrame() bytes_read = %d mismatches with VideoFrameSize = %d\n", bytes_read, m_nVideoFrameSize);
            return -1;
        }
    }

    return bytes_read;
}
Example #3
0
void Mapa::leerObjetos(const char *archivo){
	std::ifstream fileIn(archivo);
	std::string linea;
	while (std::getline(fileIn, linea)){
		std::stringstream ss(linea);
		std::string tipo;
		std::getline(ss, tipo, ',');
		std::string nombreEdificioPublico;
		if (tipo.find("edificio-publico") != std::string::npos){
			std::getline(ss, nombreEdificioPublico, ',');
		}
		std::list<Coordenada> coordenadas;

		std::string lat;
		std::string lon;
		std::getline(ss, lat, ',');
		bool continuar = std::getline(ss, lon, ',') != NULL;
		Coordenada coord(lat, lon);
		coordenadas.push_back(coord);

		while (continuar) {
			continuar &= std::getline(ss, lat, ',') != NULL;
			bool par = std::getline(ss, lon, ',') != NULL;
			if (continuar){
				if (par){
					Coordenada coord(lat, lon);
					coordenadas.push_back(coord);
				}
			}
		}
		this->crearElemento(tipo, coordenadas, lat, nombreEdificioPublico);
	}
}
Example #4
0
bool M4SCpWindow::loadFromFile(const QString &fileName)
{    
    // read data from file
    QFile fileIn(fileName);

    if (!fileIn.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::warning(0, tr("Error"),
                             tr("Can't open file %1:\n%2.")
                             .arg(fileName)
                             .arg(fileIn.errorString()));
        return false;
    }

    QTextStream in(&fileIn);
    mEditor->document()->setPlainText(in.readAll());
    fileIn.close();

    mFileName = fileName;
    setWindowTitle(mFileName + "[*]");
    mIsSaved = true;

    emitEvent(EditorObserverInterface::ContentLoaded);

    return true;
}
Example #5
0
static void DoTestRoundTrip(const T *values, size_t numValues)
{
    {
        wxFileOutputStream fileOut(wxT("test.txt"));
        wxTextOutputStream textOut(fileOut);

        for ( size_t n = 0; n < numValues; n++ )
        {
            textOut << values[n] << endl;
        }
    }

    {
        wxFileInputStream fileIn(wxT("test.txt"));
        wxTextInputStream textIn(fileIn);

        T value;
        for ( size_t n = 0; n < numValues; n++ )
        {
            textIn >> value;

            CPPUNIT_ASSERT( value == values[n] );
        }
    }
}
Example #6
0
BOOL Skeleton::LoadSkeleton(const string &filePath, const string &fileName)
{
    string file = filePath + fileName;
    ifstream fileIn(file.c_str());
    string checkString;

    int numJoints;
    int numMeshes;

    if(fileIn.fail())
    {
        MessageBox(NULL, TEXT("´ò¿ª¹Ç÷ÀÎļþʧ°Ü"), TEXT("ERROR"), MB_OK);
        return FALSE;
    }

    while( fileIn.eof() != TRUE )
    {
        checkString.clear();
        fileIn >> checkString;
        if(checkString == "MD5Version")
        {
            int version;
            fileIn >> version;
            if(version != 10)
            {
                MessageBox(0, TEXT("¹Ç÷ÀÄ£ÐÍ°æ±¾´íÎó"), TEXT("Error"), MB_OK);
                return FALSE;
            }
        }
        else if ( checkString == "commandline" )
Example #7
0
/*
========================
idSoundSample_XAudio2::LoadGeneratedSound
========================
*/
bool idSoundSample_XAudio2::LoadGeneratedSample( const idStr &filename ) {
	idFileLocal fileIn( fileSystem->OpenFileReadMemory( filename ) );
	if ( fileIn != NULL ) {
		uint32 magic;
		fileIn->ReadBig( magic );
		fileIn->ReadBig( timestamp );
		fileIn->ReadBig( loaded );
		fileIn->ReadBig( playBegin );
		fileIn->ReadBig( playLength );
		idWaveFile::ReadWaveFormatDirect( format, fileIn );
		int num;
		fileIn->ReadBig( num );
		amplitude.Clear();
		amplitude.SetNum( num );
		fileIn->Read( amplitude.Ptr(), amplitude.Num() );
		fileIn->ReadBig( totalBufferSize );
		fileIn->ReadBig( num );
		buffers.SetNum( num );
		for ( int i = 0; i < num; i++ ) {
			fileIn->ReadBig( buffers[ i ].numSamples );
			fileIn->ReadBig( buffers[ i ].bufferSize );
			buffers[ i ].buffer = AllocBuffer( buffers[ i ].bufferSize, GetName() );
			fileIn->Read( buffers[ i ].buffer, buffers[ i ].bufferSize );
			buffers[ i ].buffer = GPU_CONVERT_CPU_TO_CPU_CACHED_READONLY_ADDRESS( buffers[ i ].buffer );
		}
		return true;
	}
	return false;
}
Example #8
0
    bool _centroidAngleTest()
    {
        cvt::Resources r;

        bool result = true;

        for( size_t i = 0; i < 360; i+=5 ){
            String fileIn( "bw" );
            fileIn += i;
            fileIn += ".png";
            //std::cout << "File : " << fileIn << std::endl;
            cvt::Image _img( r.find( fileIn ) );

            cvt::Image img;
            _img.convert( img, IFormat::GRAY_UINT8 );
            cvt::ORB orb( img, 1, 0.5f, 50 );

            cvt::Image ii;
            img.integralImage( ii );

            size_t stride;
            float * ptr = ii.map<float>( &stride );

            cvt::ORBFeature feature( img.width() / 2.0f, img.height() / 2.0f );

            orb.centroidAngle( feature, ptr, stride );

            //std::cout << "Feature Angle: " << Math::rad2Deg( feature.angle ) << std::endl;

            ii.unmap<float>( ptr );

        }

        return result;
    }
Example #9
0
	void saveStaticObject(StaticObject &staticObject, const char * filename)
	{
		std::cout << "saveStaticObject in file: " << filename << std::endl;
		std::ofstream fileIn(filename, std::ios::out | std::ios::binary);
		boost::archive::binary_oarchive_pointsmap oa(fileIn);
		oa & staticObject;
		fileIn.close();
	}
Example #10
0
	void saveCamera(Camera &camera, const char * filename)
	{
		std::cout << "saveCamera in file: " << filename << std::endl;
		std::ofstream fileIn(filename, std::ios::out | std::ios::binary);
		boost::archive::binary_oarchive_pointsmap oa(fileIn);
		oa & camera;
		fileIn.close();
	}
Example #11
0
void FileCodeWriter::WriteBuffer()
{
	const static unsigned char MICROSOFT_BOM[3] = { 0xEF, 0xBB, 0xBF };

	// Compare buffer with existing file (if any) to determine if
	// writing the file is necessary
	bool shouldWrite = true;
	std::ifstream fileIn(m_filename.mb_str(wxConvFile), std::ios::binary | std::ios::in);

	std::string buf;

	if (fileIn)
	{
		MD5 diskHash(fileIn);
		unsigned char* diskDigest = diskHash.raw_digest();

		MD5 bufferHash;
		if (m_useMicrosoftBOM) {
			bufferHash.update(MICROSOFT_BOM, 3);
		}
		const std::string& data = m_useUtf8 ? _STDSTR( m_buffer ) : _ANSISTR( m_buffer );

		if (!m_useUtf8) buf = data;

		bufferHash.update( reinterpret_cast< const unsigned char* >( data.c_str() ), data.size() );

		bufferHash.finalize();

		unsigned char* bufferDigest = bufferHash.raw_digest();

		shouldWrite = ( 0 != std::memcmp( diskDigest, bufferDigest, 16 ) );

		delete [] diskDigest;

		delete [] bufferDigest;
	}

	if ( shouldWrite )
	{
		wxFile fileOut;
		if (!fileOut.Create(m_filename, true))
		{
			wxLogError( _("Unable to create file: %s"), m_filename.c_str() );
			return;
		}

		if (m_useMicrosoftBOM)
		{
			fileOut.Write(MICROSOFT_BOM, 3);
		}

		if (!m_useUtf8)
			fileOut.Write(buf.c_str(), buf.length());
		else
			fileOut.Write(m_buffer);
	}
}
Example #12
0
std::string util::readFile(const std::string &file){
	std::string content = "";
	std::ifstream fileIn(file.c_str());
	if (fileIn.is_open()){
		content = std::string(std::istreambuf_iterator<char>(fileIn),
			std::istreambuf_iterator<char>());
	}
	return content;
}
Example #13
0
int lines_count (const std::string& fileName){
    std::ifstream fileIn(fileName);
    int n =0;
    std::string line;
    while (std::getline(fileIn , line)){
        n++;
    }
    return n;
}
Example #14
0
//Reload opened file data
void MainWindow::on_actionReload_triggered()
{
    LevelData FileData;
    QString filePath;
    QRect wnGeom;

    if (activeChildWindow()==1)
    {
        filePath = activeLvlEditWin()->curFile;

        QFile fileIn(filePath);

        if (!fileIn.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(this, tr("File open error"),
        tr("Can't open the file."), QMessageBox::Ok);
            return;
        }

        FileData = FileFormats::ReadLevelFile(fileIn); //function in file_formats.cpp
        if( !FileData.ReadFileValid ){
            statusBar()->showMessage(tr("Reloading error"), 2000);
            return;}

        FileData.filename = QFileInfo(filePath).baseName();
        FileData.path = QFileInfo(filePath).absoluteDir().absolutePath();
        FileData.playmusic = GlobalSettings::autoPlayMusic;
        activeLvlEditWin()->LvlData.modified = false;
        activeLvlEditWin()->close();
        wnGeom = ui->centralWidget->activeSubWindow()->geometry();
        ui->centralWidget->activeSubWindow()->close();

        leveledit *child = createLvlChild();
        if ((bool) (child->loadFile(filePath, FileData, configs, GlobalSettings::LvlOpts))) {
            statusBar()->showMessage(tr("Level file reloaded"), 2000);
            child->show();
            ui->centralWidget->activeSubWindow()->setGeometry(wnGeom);
            updateMenus(true);
            SetCurrentLevelSection(0);

            if(GlobalSettings::autoPlayMusic) ui->actionPlayMusic->setChecked(true);
            LvlMusPlay::musicForceReset=true; //reset musics
            on_actionPlayMusic_triggered(ui->actionPlayMusic->isChecked());

        } else {
                WriteToLog(QtDebugMsg, ">>File loading aborted");
            child->show();
                WriteToLog(QtDebugMsg, ">>Window showed");
            if(activeChildWindow()==1) activeLvlEditWin()->LvlData.modified = false;
                WriteToLog(QtDebugMsg, ">>Option set");
            ui->centralWidget->activeSubWindow()->close();
                WriteToLog(QtDebugMsg, ">>Windows closed");
        }
    }

    clearFilter();
}
Example #15
0
BOOL BIniFile::LoadFile(const char *const fileName)
{
    BZ_CHECK_C_STRING_RETURN_BOOL(fileName);
    
    std::ifstream fileIn(fileName);
    if (!fileIn)
    {
        assert(false);
        return FALSE;
    }

    char   buffer[LINE_BUFFER_SIZE];
    bool   getSeg  = false;
    size_t nBufLen = 0; 
    int    nAssPos = 0;
    while (!fileIn.eof())
    {
        fileIn.getline(buffer, LINE_BUFFER_SIZE);
        if ((!getSeg) && (!IsSegment(buffer)))
        {
            continue;
        }

        if (IsComment(buffer))
        {
            continue;
        }

        if (IsSegment(buffer))
        {
            BSegmentNode seg;
            getSeg              = true;
            nBufLen             = strlen(buffer);
            buffer[nBufLen - 1] = '\0';
            seg.m_bssSeg = BSimpleString(buffer + 1);

            m_segArray.push_back(seg);
            continue;
        }

        if (-1 != (nAssPos = IsKeyNode(buffer)))
        {
            BKeyNode key;
            buffer[nAssPos] = '\0';
            key.m_bssKey     = BSimpleString(buffer);
            key.m_bssValue   = BSimpleString(buffer + nAssPos + 1);
            m_segArray.back().AddKey(key);
            continue;
        }
    }

    fileIn.close();
    return TRUE;
}
string ReadFile(const string& filename){
    ifstream fileIn(filename);

    if (!fileIn.good()){
		cerr << "Could not load shader: " << filename << endl;
		return "";
    }

    string stringBuffer(istreambuf_iterator<char>(fileIn), (istreambuf_iterator<char>()));
	return stringBuffer;
}
Example #17
0
string GLSLProgram::ReadFile( const string& filename )
{
	ifstream fileIn(filename.c_str());

	if (!fileIn.good())
	{
		PRINT_WARN("Shader %s Error", filename.c_str());
		return string();
	}

	string stringBuffer(std::istreambuf_iterator<char>(fileIn), (std::istreambuf_iterator<char>()));
	return stringBuffer;
}
Example #18
0
void Block::readFile(const std::string& fileName, int blockOffset)
{
	initialize();

	std::fstream fileIn(fileName.c_str(), std::ios::in);
	fileIn.seekg(blockOffset*BLOCK_SIZE, std::ios::beg);
	fileIn.read(content, BLOCK_SIZE);
	fileIn.close();
	isPinned = 0;
	isDirty = 0;
	this->fileName = fileName;
	this->blockOffset = blockOffset;
}
Example #19
0
bool Terrain::loadHeightmap(const string& rawFile, int width) 
{
    const float HEIGHT_SCALE = 10.0f; 
    std::ifstream fileIn(rawFile.c_str(), std::ios::binary);

    if (!fileIn.good()) 
    {
        std::cout << "File does not exist" << std::endl;
        return false;
    }

    
    string stringBuffer(std::istreambuf_iterator<char>(fileIn), (std::istreambuf_iterator<char>()));

    fileIn.close();

    if (stringBuffer.size() != (width * width)) 
    {
        std::cout << "Image size does not match passed width" << std::endl;
        return false;
    }

    vector<float> heights;
    heights.reserve(width * width); 

    
    for (int i = 0; i < (width * width); ++i) 
    {
        
        float value = (float)(unsigned char)stringBuffer[i] / 256.0f; 
    
        heights.push_back(value * HEIGHT_SCALE);
        m_colors.push_back(Color(value, value, value));
    }

    glGenBuffers(1, &m_colorBuffer); 
    glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer); 
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * m_colors.size() * 3, &m_colors[0], GL_STATIC_DRAW); 

    generateVertices(heights, width);
    generateIndices(width);
    generateTexCoords(width);
    generateNormals();

    generateWaterVertices(width);
    generateWaterIndices(width);
    generateWaterTexCoords(width);

    m_width = width;
    return true;
}
    void fileImportErrors() {
        QFETCH(QString, file);
        QFETCH(QString, error);

        QString filename = ":/data/errors/";
        filename += file;
        QFile fileIn(filename);
        fileIn.open(QIODevice::ReadOnly);

        bool result = m_handler->importData(&fileIn);

        QVERIFY(!result);
        QCOMPARE(m_handler->errorString(), error);
    }
Example #21
0
//template <class SerializeType>
void saveTranslatedMeshDataList(std::list<TranslatedMeshData> &transMesh, const char * filename, const int fileType)
{
	if (fileType == DELAUNAYVORONOI_BINARY_FILE_TYPE)
	{
		std::ofstream fileIn(filename, std::ios::out | std::ios::binary);
		//boost::archive::binary_oarchive oa(fileIn); //take a look into the boost::serialization::save template block in DelaunayVoronoi.h
		boost::archive::binary_oarchive_pointsmap oa(fileIn);
		oa & transMesh;
		fileIn.close();
	}
	else if (fileType == DELAUNAYVORONOI_TEXT_FILE_TYPE)
	{
		std::ofstream fileIn(filename, std::ios::out);
		//boost::archive::text_oarchive oa(fileIn); //take a look into the boost::serialization::save template block in DelaunayVoronoi.h
		boost::archive::text_oarchive_pointsmap oa(fileIn);
		oa & transMesh;
		fileIn.close();
	}
	else
	{
		std::cout << "   Error: Unsuppoerted file type!" << std::endl;
	}
}
Example #22
0
bool MzidentmlReader::checkIsMeta(const std::string &file) {
  //NOTE assuming the file has been tested before
  bool isMeta;
  std::ifstream fileIn(file.c_str(), std::ios::in);
  std::string line;
  getline(fileIn, line);
  fileIn.close();
  //NOTE this is not the best way to check if it is meta for mzident
  if (line.find("<?xml") != std::string::npos) {
    isMeta = false;
  } else {
    isMeta = true;
  }
  return isMeta;
}
Example #23
0
	bool FeatureCapture::readTemplateFile(const string & templateFileName)
	{
		std::ifstream fileIn(templateFileName.c_str());
		char charBuffer[8096];
		while (fileIn.getline(charBuffer, 8096))
		{
			string templateStr = charBuffer;
			if (templateStr == "End")break;
			if (templateStr.size() && templateStr[0] == 'U')
				featureIndexPtr->unigramTempls.push_back(templateStr);
			if (templateStr.size() && templateStr[0] == 'B')
				featureIndexPtr->bigramTempls.push_back(templateStr);
		}
		return true;
	}
Example #24
0
bool MsgfplusReader::checkValidity(const std::string &file) {

  bool isvalid = true;
  std::ifstream fileIn(file.c_str(), std::ios::in);
  if (!fileIn) {
    ostringstream temp;
    temp << "Error : can not open file " << file << std::endl;
    isvalid = false;
    throw MyException(temp.str());
  }
  std::string line;
  if (!getline(fileIn, line)) {
    ostringstream temp;
    temp << "Error : can not read file " << file << std::endl;
    isvalid = false;
    throw MyException(temp.str());
  }
  if (line.find("<?xml") == std::string::npos) {
    fileIn.close();
    ostringstream temp;
    temp << "Error : the input file is not xml format " << file << std::endl;
    isvalid = false;
    throw MyException(temp.str());
  }
  else //Test whether Sequest or MS-GF+ format
  {
    std::string line2, line3;
    getline(fileIn, line2);
    getline(fileIn, line3);

    if ((line2[1] != '!' && line2.find("MS-GF+") != std::string::npos && line2.find("MzIdentML") != std::string::npos)
         || (line3[1] != '!' && line3.find("MS-GF+") != std::string::npos && line3.find("MzIdentML") != std::string::npos))
    {
      if(VERB > 2)
        std::cerr << "MzIdentML - MSGF+ format" << std::endl;
      isvalid = true;
    } else {
      fileIn.close();
      ostringstream temp;
      temp << "Error : the input file is not MzIdentML - MSGF+ format " << file << std::endl;
      isvalid = false;
      throw MyException(temp.str());
    }

  }
  fileIn.close();
  return isvalid;
}
Example #25
0
Blob<char> FileUtil::File2Buffer(const std::string& filePath)
{
	CFileInputStream fileIn(filePath.c_str());

	long fileLength = fileIn.available();

	Blob<char> blob;

	blob.setData(auto_array_ptr<char>(new char[fileLength]),fileLength);

	fileIn.read((unsigned char*)blob.get(),fileLength);

	fileIn.close();

	return blob;
}
Example #26
0
bool PbPersistenceManager::loadScene(const QString& filePath)
{	
	if (!exists(filePath))
		return false;

	PbBumpTop bumptop;

	// read the bumptop root from disk
	std::ifstream fileIn(filePath.utf16(), ios::binary);
	if (!bumptop.ParseFromIstream(&fileIn))
	{
		fileIn.close();
		return false;
	}
	fileIn.close();

	// deserialize the header (for debugging mostly)
	if (bumptop.has_header())
	{
		const PbHeader& header = bumptop.header();
		QString buildStr;
		if (header.has_build())
			buildStr = qstring(header.build());
		unsigned int versionNumber = 0;
		if (header.has_version())
			versionNumber = header.version();
	}

	// deserialize the scene data
	if (bumptop.has_scene())
	{
		if (!scnManager->deserializeFromPb(&bumptop.scene()))
		{
			assert(false);
			return false;
		}
	}

	// cross reference the files in the scene data with the files actually
	// in the working directory
	scnManager->crossReference();
	sel->clear();

	LOG("PbPersistenceManager::loadScene successful");
	return true;
}
Example #27
0
void Mesh::load_mesh(const char* i_sFilePath)
{
	//Indice vectors
	std::vector<U16>	l_PositionIndices;
	std::vector<U16>	l_TexCoordIndices;
	std::vector<U16>	l_NormalIndices;

	bool l_bHasTexCoord		= false;
	bool l_bHasPosition		= false;
	bool l_bHasNormals		= false;

	//Vertex vectors
	std::vector<Vec3f>	l_Positions;
	std::vector<Vec2f>	l_TexCoords;
	std::vector<Vec3f>	l_Normals;

	std::ifstream fileIn(i_sFilePath);
	
	
	//Check if filed open properly
	if(!fileIn.is_open())
	{
		std::cerr << "Cannot open " << i_sFilePath << std::endl;
		return;
		exit(1);
	}

	
	
	//line will hold each line of the .obj file consecutively
	std::string line = "";

	//Parse the whole file...
	while (std::getline(fileIn,line))
	{
		//Position
		if(line.substr(0,2) == "v ")
		{
			l_bHasPosition = true;
			std::istringstream s(line.substr(2));
			Vec3f v; s >> v.x; s >> v.y; s >> v.z;
			l_Positions.push_back(v);

		}
		//Load texture coordinates
		else if(line.substr(0,2) == "vt")
Example #28
0
void Solver::SatBaseClass::readSolutionOther(const std::string &solutionFile){
    std::string line;
    std::ifstream fileIn ( solutionFile );
    while(!fileIn.eof()){

        std::getline( fileIn, line );
        if(line.empty()) continue;
        if(line[0] == 'c') continue;
        if(line[0] == 's') {
            std::transform(line.begin(), line.end(), line.begin(), ::tolower);
            if(line.find("unsat") != std::string::npos){
                throw Exception::StringException("UNSAT");
                std::cerr << line << std::endl;
                break;
            }
        }
        if(line[0] == 'v'){

            line = line.substr(2);
            std::vector<std::string> solution = split( line, ' ');
            for( const std::string& s : solution )
            {
                if(s.empty()) continue;
                if( s == "0")
                {
                    break;
                }

                // skip negativ vars
                if( s[0] == '-' ) continue;

                uint varAsInt = std::stoi(s)-1;
                if(varAsInt == getTrueVar()) continue;
                if(varAsInt == 0) continue;
                if(varAsInt >= intToVar.size()) break;

                PosInt varAsPos =  intToVar[varAsInt];
                std::cout << "Ausgabe der Pos " << varAsInt << ": " << varAsPos << std::endl;
                gameField.getTileById(varAsPos.getValue()).setSolutionX(varAsPos.getX());
                gameField.getTileById(varAsPos.getValue()).setSolutionY(varAsPos.getY());


            }
        }
    }
}
Example #29
0
//_________________________________________________________________________________________________
TChain* CreateChainFromText(const char *fileName, const char *treeName, Int_t nread, Int_t nskip)
{
//
// Create a TChain with all required files listed into a text file.
// Necessary to run analysis in local jobs.
// ---
// Arguments:
//  - xmlFileName = input file list
//  - treeName    = "esdTree" or "aodTree"
//  - nread       = how many files to read (0 = all)
//  - nskip       = how many files to skip from beginning
//

  // if third argument is 0, it is interpreted
  // as "read all lines"
  Bool_t readAll = (nread <= 0);
  
  // initialize output object
  TChain* target = new TChain(treeName);
  
  // open text file
  ifstream fileIn(fileName);
  
  // loop on collection
  TString line;
  while (fileIn.good())
  {
    fileIn >> line;
    if (line.IsNull()) continue;
    
    // skip until reached required number of offset
    if (nskip > 0) {--nskip; continue;}
    
    // stop if required number of read files is reached
    // otherwise update the counter
    if (!readAll && nread <= 0) break;
    nread--;
    
    // add file
    Info("CreateChainFromText", "Adding '%s'", line.Data());
    target->Add(line.Data());
  }
  
  return target;
}
Example #30
0
ResultCode FileReadBuffer::restore(const boost::filesystem::path& pathFile)
{
  if (!exists(pathFile) || !is_regular(pathFile))
  {
    return rcFailure;
  }

  std::ifstream fileIn(pathFile.string().c_str(), std::ios::binary);
  if (!fileIn)
  {
    return rcFailure;
  }
  uiPos_ = 0;
  uiSize_ = 4096;
  char pTemp[4096];
  while (true)
  {
    fileIn.read(pTemp, uiSize_);
    if (fileIn.bad())
    {
      return rcFailure;
    }

    size_t uiCount = fileIn.gcount();
    if (uiCount == 0)
      break;
    Buffer* pNewBuffer = new Buffer[uiPos_ + uiCount];
    memcpy(pNewBuffer, pBuffer_, uiPos_);
    memcpy(pNewBuffer+uiPos_, pTemp, uiCount);
    delete[] pBuffer_;
    pBuffer_ = pNewBuffer;
    uiPos_ += uiCount;

    if (uiCount < uiSize_)
      break;
  }

  uiSize_ = uiPos_;
  uiPos_ = 0;

  fileIn.close();

  return rcSuccess;
}