/**
 * @brief   determine the number of resources (BITMAPs and SOUNDs)
 * @param   rcfile          reference to a open rc file
 * @param   hfile           reference to a open header file
 * @param   rcBitmapCount   reference to the Bitmap counter (rc file)
 * @param   rcSoundCount    reference to the Sound counter  (rc file)
 * @param   hBitmapCount    reference to the Bitmap counter (h file)
 * @param   hSoundCount     reference to the Sound counter  (h file)
 */
void determineResourceCount(ifstream& rcfile, ifstream& hfile,
    int& rcBitmapCount, int& rcSoundCount,
    int& hBitmapCount, int& hSoundCount)
{
    string Line;
    
    // count resources (i.e. BITMAPs and SOUNDs) in rc file
    while (rcfile.good()) {
        getline(rcfile, Line);
        
        if ((int)Line.find("DISCARDABLE") != -1)
        {
            if ((int)Line.find("BITMAP") != -1)
                rcBitmapCount++;
            else if ((int)Line.find("SOUND") != -1)
                rcSoundCount++;
        }
    }
    
    // count resources (i.e. BITMAPs and SOUNDs) in header file
    while (hfile.good()) {
        getline(hfile, Line);
        
        if ((int)Line.find("#define") != -1)
        {
            if ((int)Line.find("BMP_") != -1)
                hBitmapCount++;
            else if ((int)Line.find("SND_") != -1)
                hSoundCount++;
        }
    }
}
Exemple #2
0
//====================================================================
// Load network from file
//====================================================================
bool BPNet::load( ifstream &ist )
{
	if ( !ist.good() )
		return false;
	
	int numLayers	= 0;
	int numNodes	= 0;
	int numLinks	= 0;

	ist >> numLayers;	// num layers
	
	vector<int> layers(numLayers);
	for(int i = 0; i != numLayers; ++i)
		ist >> layers[i];	// number of nodes in each layer

	ist >> numNodes;
	ist >> numLinks;

	// create network structure (nodes and links)
	createNetwork(0, 0, layers);
	
	// load nodes data
	for (i = 0; i != numNodes; ++i)
		_nodes[i]->load(ist);

	// load links data
	for(i = 0; i != numLinks; ++i)
		_links[i]->load(ist);


	if (!ist.good())
		return false;

	return true;
}
  static void readGrammar(ifstream& infile, map<string, Definition>& grammar)
  {   
    // Keep parsing until EOF is reached.
    while(infile.good())
    { 
      // Ignore all chars until '{' is reached.
      infile.ignore(numeric_limits<streamsize>::max(), '{');

      // Ignore all chars until '\n' is reached.
      infile.ignore(numeric_limits<streamsize>::max(), '<');

      if(infile.good()) 
      {
        // Beginning of a definition; parse into program.
        Definition myDefinition = Definition(infile);
        
        // Fill map.
        string myNonTerminal = myDefinition.getNonterminal();
        pair<string, Definition> myPair(myNonTerminal, myDefinition);
        grammar.insert(myPair);
      }
    }

    infile.close();
}
Exemple #4
0
Meeting::Meeting(ifstream& is, const Participants_t& people) {
    int number_of_participants;
    is >> m_time >> m_topic >> number_of_participants;
    if (!is.good()) {
        throw Error("Invalid data found in file!");
    }

    for (int i = 0; i < number_of_participants; ++i){
        String lastname;

        is >> lastname;
        if (!is.good()) {
            throw Error("Invalid data found in file!");
        }

        Person person(lastname);
        auto iter = people.find(&person);
        if (iter == people.end()) {
            throw Error("Invalid data found in file!");
        }
        else {
            participants.insert(*iter);
        }
    }
}
bool readPlayerFromBinary(Player& player, ifstream& input)
{
    assert(input.good());
    Player plr;
    input.read((char*)&plr, sizeof(plr));
    bool result = input.good() && input.gcount() == sizeof(plr);
    if (result) player = plr;
    return result;
}
bool MlMaximumEntropyModel::readModel(ifstream& ifs)
{
	char buffer[256];
	while (ifs.good())
	{
		ifs.getline(buffer,256);
		if (ifs.gcount()>0 && buffer[0]!='#')
			break;
	}
		
	unsigned int numClasses=0;
	if (sscanf(buffer,"MAXIMUM_ENTROPY %u",&numClasses) != 1)
	{
		cout << "Bad line in model file:" << endl << buffer << endl;
		return false;
	}

	weights_.resize(numClasses);
	for (size_t c=0; c<numClasses; c++)
	{
		ifs.getline(buffer,256);
		unsigned int numWeights=0;
		if (sscanf(buffer,"%u",&numWeights) != 1)
		{
			cout << "Bad line in model file:" << endl << buffer << endl;
			return false;
		}
		weights_[c].resize(numWeights,0.0);
		while (ifs.good())
		{
			ifs.getline(buffer,256);
			if (! strncpy(buffer,"END_",4))
				break;
			if (ifs.gcount() == 0 || buffer[0] != 'F')
				continue;

			size_t index;
			float  weight;
			istringstream iss(buffer+1);
			iss >> index >> weight;
			if (iss.fail())
			{
				if (strlen(buffer)<3)
					continue;

				cout << "Bad line in model file:" << endl << buffer << endl;
				return false;
			}
			if (index>weights_[c].size())
				error("Bad feature index in line: ",buffer);

			weights_[c][index]=weight;
		}
	}
	return true;
}
Exemple #7
0
/**
 * reads char stream to bit stream using previous method
 */
void bin2str(ifstream & ifs,deque<char> & ss)
{
	char aux = 0;
	while(ifs.good())
	{
		aux=ifs.get(); if(!ifs.good()) break;
		string  tmp = ascii2bin(aux);
		ss.insert(ss.end(),tmp.data(),tmp.data()+tmp.length());
	}
}
/// <summary>
/// Checks if all files are in place.
/// </summary>
int isAllReady()
{
	br_file_old = ifstream("DOT_BR_OLD.txt");
	en_file_old = ifstream("DOT_EN_OLD.txt");

	if (!br_file_old.good() || !en_file_old.good())
	{
		cout << "ERROR: Files are not in place!" << endl;
		cout << "Please put DOT_BR_OLD.txt and DOT_EN_OLD.txt in this same folder!" << endl;
		return false;
	}

	return true;
}
int createC1(char *inpFileName, vector<int>& rowVec, vector<short>& colVec, int& noOfTrans, set<int>& itemsSet, map<int,int>& C1 ){

	inpFileStream.open(inpFileName);
	if(!inpFileStream.good()){
		inpFileStream.close();
		cout<<"While Generating C1"<<endl;
		cout<<"Error in opening datafile or datafile doesn't exists"<<endl;
		return 1;
	}
	
	vector<int> dataLine;
	u_int dataLen;
	map<int,int>::iterator C1Iter;
	while(readLineFromFile(dataLine, dataLen)){
		if(dataLen){
			rowVec.push_back(dataLen + rowVec[noOfTrans]);
			++noOfTrans;
		}
		for(int i = 0; i < dataLen; ++i){
			colVec.push_back((short)dataLine[i]);
			itemsSet.insert(dataLine[i]);
			if((C1Iter = C1.find(dataLine[i])) != C1.end()){
				++((C1Iter)->second);
			}
			else
			++C1[dataLine[i]];
		}
	}	
	inpFileStream.close();
	
	return 0;
}
Exemple #10
0
void initStreams()
{
#ifdef _WIN32
    string parametersFileName("parametersExpTexturingParabolicCylinderAdjustment.txt");
#endif
#ifdef __linux__
    string parametersFileName("/home/carlo/Desktop/params/parametersExpTexturingParabolicCylinderAdjustment.txt");
#endif
    inputParameters.open(parametersFileName.c_str());
    if ( !inputParameters.good() )
    {
        cerr << "File " << parametersFileName << " doesn't exist, enter a valid path, press Enter to exit" << endl;
        std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
        exit(0);
    }
    parameters.loadParameterFile(inputParameters);

    string subjectName = parameters.find("SubjectName");
    string outputFilename = parameters.find("BaseDir")+string("responseFileAdjustment_") + subjectName + string(".txt");
    if ( util::fileExists(outputFilename) )
    {
        int i=0;
        cerr << "file " << outputFilename << "already exists, press Enter to quit" << endl;
        std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
        exit(0);
    }
    else
    {
        responseFile.open( outputFilename.c_str() );
        responseFile << "TrialNumber\tCurrCurvature\tIODFactor\tAdjustedCurvatureZ" << endl;
    }
}
bool Serializer::readInt(ifstream &infile, int &ret) {
	unsigned char buf[4];
	infile.read((char *)buf, 4);
	if (!infile.good())
		return false;

	// Integer is stored in big-endian format

	// See if it's positive or negative. If the first bit is 1 then it's negative
	bool neg = ((buf[0] >> 7) == 1);
	buf[0] = buf[0] & 0x7f;

	int newRet = 0;
	newRet += buf[3] * ONE_SHIFT_ZERO;
	newRet += buf[2] * ONE_SHIFT_ONE;
	newRet += buf[1] * ONE_SHIFT_TWO;
	newRet += buf[0] * ONE_SHIFT_THREE;

	if (neg)
		newRet = -newRet;

	ret = newRet;

	return true;
}
void GrowToolbar::open( ifstream& fp)
{
  int		type;
  int 		end_found = 0;
  char		dummy[40];

  for (;;)
  {
    if ( !fp.good()) {
      fp.clear();
      fp.getline( dummy, sizeof(dummy));
      printf( "** Read error GrowToolbar: \"%d %s\"\n", type, dummy);      
    }

    fp >> type;
    switch( type) {
      case glow_eSave_GrowToolbar: break;
      case glow_eSave_GrowToolbar_grownode_part: 
        GrowNode::open( fp);
        break;
	// case glow_eSave_GrowToolbar_nc: 
        // nc = new GlowNodeGroup( ctx, n_name);
        // nc->open( fp);
        // break;
      case glow_eSave_End: end_found = 1; break;
      default:
        cout << "GrowToolbar:open syntax error" << endl;
        fp.getline( dummy, sizeof(dummy));
    }
    if ( end_found)
      break;
  }
}
Exemple #13
0
/*!
  \param fp	Input file.
*/
void GrowXYCurve::open( ifstream& fp)
{
  int		type;
  int 		end_found = 0;
  char		dummy[40];

  for (;;)
  {
    if ( !fp.good()) {
      fp.clear();
      fp.getline( dummy, sizeof(dummy));
      printf( "** Read error GrowXYWindow: \"%d %s\"\n", type, dummy);      
    }

    fp >> type;
    switch( type) {
      case glow_eSave_GrowXYCurve: break;
      case glow_eSave_GrowXYCurve_trend_part: 
        GrowTrend::open( fp);
        break;
      case glow_eSave_End: end_found = 1; break;
      default:
        cout << "GrowXYCurve:open syntax error" << endl;
        fp.getline( dummy, sizeof(dummy));
    }
    if ( end_found)
      break;
  }
}
Exemple #14
0
int _main() {

	while (dictin.good()) {
		string word;
		dictin >> word;
		dict.push_back(word);
	}

	char charNumMapping[][3] = { { ' ', ' ', ' ' }, { ' ', ' ', ' ' }, { 'A',
			'B', 'C' }, { 'D', 'E', 'F' }, { 'G', 'H', 'I' },
			{ 'J', 'K', 'L' }, { 'M', 'N', 'O' }, { 'P', 'R', 'S' }, { 'T',
					'U', 'V' }, { 'W', 'X', 'Y' } };

	string num;
	fin >> num;

	found = false;

	printAllCombinations(num, charNumMapping);

	if (!found) {
		fout << "NONE" << endl;
	}

	return 0;
}
void GlowCustomColors::open( ifstream& fp)
{
  int		type;
  int 		end_found = 0;
  char		dummy[40];
  int 		csize = 0;

  for (;;)
  {
    if ( !fp.good()) {
      fp.clear();
      fp.getline( dummy, sizeof(dummy));
      printf( "** Read error GlowCustomColors: \"%d %s\"\n", type, dummy);      
    }

    fp >> type;
    switch( type) {
      case glow_eSave_CustomColors: break;
      case glow_eSave_CustomColors_colortheme_lightness: fp >> colortheme_lightness; break;
      case glow_eSave_CustomColors_is_default_colortheme: fp >> is_default_colortheme; break;
      case glow_eSave_CustomColors_colors_size: fp >> csize; break;
      case glow_eSave_CustomColors_colors:
	for ( int i = 0; i < csize; i++) {
	  fp >> colors[i][0]; fp >> colors[i][1]; fp  >> colors[i][2];
	}
	break;
      case glow_eSave_End: end_found = 1; break;
      default:
        cout << "GlowCustomColors:open syntax error" << endl;
        fp.getline( dummy, sizeof(dummy));
    }
    if ( end_found)
      break;
  }
}
Exemple #16
0
//private function called by load(). Passed parameter is the file (ifstream) as imported by load()
//returns integer of number of columns and rows. Returns negative value if invalid grid
int Grid::getSize(ifstream& sourceFile)
{
	int puzSize=0, rowLength;
	string tempString;

	//count how many rows of text
	while(sourceFile.good()){
		getline(sourceFile, tempString);
		puzSize++;
	}
	
	sourceFile.seekg(0,ios::beg);	//move cursor back to beginning
	sourceFile.clear();				//clear error flags
	
	//go through each line again, checking there are the right number of columns in each row
	while(!sourceFile.eof()){
		getline(sourceFile, tempString);
		rowLength = tempString.length();
		if(rowLength!=puzSize){ //if # of columns does not match # of rows
			cout << "Wrong number of columns in this row: "<<tempString<<endl;
			return -1; //if there is a problem, return negative number (and exit)
		}
	}
	sourceFile.seekg(0,ios::beg);	//when finished, make sure to leave cursor at beginning of file
	sourceFile.clear();				//clear error flags
	return puzSize;
}
Exemple #17
0
	BitString::BitString(ifstream & input) {
		assert(input.good());
		input.read((char*)&length,sizeof(size_t));
		input.read((char*)&uintLength,sizeof(size_t));
		data = new uint[uintLength];
		input.read((char*)data,uintLength*sizeof(uint));
	}
void getVarsDeclaration(ifstream &file)
{ //var ja foi consumido
string token;
//----------------------------
file >> token; // "name?"
file.putback(token.length()); // retorna "name?"
if (token==";")
	{
	cout << "expected: variable identifier" <<endl;
	exit(0);
	}

while (token!=";" && file.good())
{
file >> token; // name
file >> token; // separador ou terminador
if (token!="," && token!=";")
	{
	cout << "expected: variable identifier separator or declaration terminator" <<endl;
	exit(0);
	}
file.unget(); //putback the ;	
}

}
///function header
void getFunctionParmList(ifstream &file)
{
string token;
bool end=false;
file >> token;
if (token!="(")
{
cout << "synthax error: parameter list opener not found in "<<currentfunction->name << endl;
exit(0);
}

while (file.good())
{
file >> token;
if (token==")") break;
currentfunction->numparms++;
file >> token;
if (token==")") break;
if (token!=",")
	{
	cout << "expected: parameter separator" <<endl;
	exit(0);
	}
}

}
Exemple #20
0
bool f_filterBase::doFilter(ifstream &in, ofstream &out)
   {
   // vars
   bool success = false;   // indicates at least one char processed.

   // open the files, if they open, proceed
   openFile(inFName, in);

   if(in.good())
     {
     // open the output file
     openFile(outFName, out);  
  
     // perform filtering
     success = readWrite(in, out);   
     }
   else   // indicate that file filtering failed
     {
     cout << "File filtering failed" << endl;
     holdProg();
     return success;
     }
   
   // close the files
   in.close();
   out.close();

   // return success
   return success;
   }
Exemple #21
0
void GlowNodeGroup::open( ifstream& fp)
{
  int		type;
  int 		end_found = 0;
  char		dummy[40];

  for (;;)
  {
    if ( !fp.good()) {
      fp.clear();
      fp.getline( dummy, sizeof(dummy));
      printf( "** Read error GlowNodeGroup: \"%d %s\"\n", type, dummy);      
    }

    fp >> type;
    switch( type) {
      case glow_eSave_NodeGroup: break;
      case glow_eSave_NodeGroup_nodeclass_part: 
        GlowNodeClass::open( fp);
        break;
      case glow_eSave_End: end_found = 1; break;
      default:
        cout << "GrowGroup:open syntax error" << endl;
        fp.getline( dummy, sizeof(dummy));
    }
    if ( end_found)
      break;
  }
}
 void ReadPPM::readFirstNonCommentLine(ifstream& stream, char* buffer, const int bufsize)
 {
    do { // read at least one line
       stream.getline(buffer, bufsize);
    } while(stream.good() && (buffer[0] == '#')); // continue while comment
    // now we have read the first non-comment line into the buffer.
 }
Exemple #23
0
//PULSE (<amplitude 1> <amplitude 2> <atraso> <tempo de subida> <tempo de descida> <tempo ligada> <período> <número de ciclos>)
void Tensao::carregaParamPULSE(ifstream &arq)
{
	int i = 0;
	while(arq.good() && arq.peek() != '\n')
	{
		//ignora os parenteses
		if (arq.peek() == ' ' || arq.peek() == '(' || arq.peek() == ')')
		{
			arq.ignore();
			continue;
		}
		switch(i)
		{
			case 0: 
				arq >> m_amplitude;
				break;
			case 1: 
				arq >> m_amplitude2;
				break;
			case 2: 
				arq >> m_atraso;
				break;
			case 3: 
				arq >> m_t_subida;
				break;
			case 4: 
				arq >> m_t_descida;
				break;
			case 5: 
				arq >> m_t_ligada;
				break;
			case 6: 
				arq >> m_periodo;
				break;
			case 7: 
				arq >> m_ciclos;
				break;
			default:
				arq >> m_ignora;
				break;
		}
		i++;
	}
	if(i!=8)
	{
		cout<< m_nome <<" PULSE: Numero de parametros errado" << i << "/8"<<endl;
		arq.close();
		m_erro = true;
	}

	cout<<m_nome<<" PULSE:"<<m_nome_a<<" "<<m_nome_b
		<<" "<<m_amplitude
		<<" "<<m_amplitude2
		<<" "<<m_atraso
		<<" "<<m_t_subida
		<<" "<<m_t_descida
		<<" "<<m_t_ligada
		<<" "<<m_periodo
		<<" "<<m_ciclos<<endl;
}
Exemple #24
0
void NaiveBayes::ignoreFieldNamesFromFirstLine(ifstream &trainFile) {
	char currentChar;

	while (trainFile.good() && currentChar != '\n') {
		currentChar = (char)trainFile.get();
	}
}
Exemple #25
0
/**
 * run a prepared statement on everything in a file
 */
timer runScriptFile(sqlite3 *db, sqlite3_stmt *pstmt, ifstream &input, int num, string type, int idx) {
	string param;
	timer t = timer();

	while (getline(input, param)) {
		// Hit EOF or error
		if (!input.good()) break;

		t.start();
		for (int i = 1; i <= num; i++)
			if(type.compare("int") == 0)
				checkErr(sqlite3_bind_int(pstmt, i, atoi(param.c_str())), __LINE__, db);
			else
				checkErr(sqlite3_bind_text(pstmt, i, param.c_str(), -1, NULL), __LINE__, db);

		while (sqlite3_step(pstmt) == SQLITE_ROW);
		checkErr(sqlite3_reset(pstmt), __LINE__, db);
		t.end();
	}

	t.start();
	checkErr(sqlite3_finalize(pstmt), __LINE__, db);
	t.end();

	return t;
}
Exemple #26
0
z main() { z maxLvl;
    if(!in.good()){cerr<<"Can't open file."; Yay!1;}
    nextPrime.push_back(2);for(z i=3;i<8;i+=2) nextPrime.push_back(i);
    in>>maxLvl;
    for(z i=0;i<maxLvl-1;i++)advancePrime();
    for(z i=0;i<nextPrime.size();i++)out<<nextPrime[i]<<endl;
}
Exemple #27
0
string loadSched(ifstream &infile, char sched[][4], const int &SLOT, 
        const int &DAY, const int &MAX_NAME, char choice[], bool &isLoaded){
    do{
        cout << "Enter the profile name to view: ";
        char fName[MAX_NAME];
        cin.get(choice, '\n');
        if(strncmp(choice, "Jeff", MAX_NAME) == 0){
            strncpy(fName, "sched_J_001.dat", MAX_NAME);
        }
        else if(strncmp(choice, "Ann", MAX_NAME) == 0){
            strncpy(fName, "sched_E_001.dat", MAX_NAME);
        }
        infile.open(fName);
        if(infile.good()){
            isLoaded = true;
        }
        else{
            isLoaded = false;
            infile.clear();
        }
    }while(!isLoaded);
    getSched(infile, sched, SLOT, DAY);
    infile.close();
    return choice;
}
//------------------------------------------------------------------------
int main(int argc, char** argv)
{
    
    string str;
    vector<string> urls;

    instream.open(argv[1]);
    outstream.open(argv[2]);


    if (instream.fail()){
          cout << "failed to open file" << endl;
          exit(1);
    }
  
    while (instream.good()) {
        instream >> str;
        if(str.find(IMG_MARKER) != string::npos) {
            if(!isDupe(extractURL(str), urls)){
                urls.push_back(extractURL(str));
            }
        }
    }  
    
    for(size_t i = 0; i < urls.size(); i++){
        outstream << urls[i] << endl;
    }

    instream.close();
    outstream.close();
  
    return 0;
}
Exemple #29
0
bool CBaseMatriz::AbreArquivo (ifstream & fin, string nomeArquivo) { // Abre arquivo formato correto
	fin.open (nomeArquivo.c_str (), ios::binary); //abrindo sempre em modo binário para que tellg e seekg funcionem corretamente no windows
	return fin.good ();
	/*string aux;
	if (fin.good ()) { // Se carregou corretamente o arquivo
		return true;
		fin >> aux;		//  Lê a primeira string ( Pi ou Di ou Vi -> P1,P2,...D1,D5...V1,V3...)
		cerr << "aux=" << aux << endl;
		if (aux[0] == 'V' || aux[0] == 'P' || aux[0] == 'D') { //se for arquivo de matriz válida.
			if ( aux.at(1) == '1' || aux.at(1) == '2' || aux.at(1) == '3' ) { // se o formato do dados for ASCII
				fin.seekg (0, ios::beg);	//  vai para posicao 0, a partir do inicio do arquivo
				return true;
			} else if ( aux.at(1) == '4' || aux.at(1) == '5' || aux.at(1) == '6') { // Verifica se o formato é BINÁRIO
				fin.close (); //  Fecha o arquivo e
				fin.open (nomeArquivo.c_str (), ios::binary); // Reabre como binario
				if (fin.good ())
					return true;
				else
					return false;
			}
		}
		fin.close (); 		// Arquivo inválido. Fechar...
	}
	return false;			//  nao abriu corretamente retorna erro
	*/
}
Exemple #30
0
void GrowSlider::open( ifstream& fp)
{
  int		type;
  int 		end_found = 0;
  char		dummy[40];
  int		tmp;

  for (;;) {
    if ( !fp.good()) {
      fp.clear();
      fp.getline( dummy, sizeof(dummy));
      printf( "** Read error GrowSlider: \"%d %s\"\n", type, dummy);      
    }

    fp >> type;
    switch( type) {
      case glow_eSave_GrowSlider: break;
      case glow_eSave_GrowSlider_direction: fp >> tmp; 
	direction = (glow_eDirection)tmp; break;
      case glow_eSave_GrowSlider_max_value: fp >> max_value; break;
      case glow_eSave_GrowSlider_min_value: fp >> min_value; break;
      case glow_eSave_GrowSlider_max_pos: fp >> max_pos; break;
      case glow_eSave_GrowSlider_min_pos: fp >> min_pos; break;
      case glow_eSave_GrowSlider_grownode_part: 
        GrowNode::open( fp);
        break;
      case glow_eSave_End: end_found = 1; break;
      default:
        cout << "GrowSlider:open syntax error" << endl;
        fp.getline( dummy, sizeof(dummy));
    }
    if ( end_found)
      break;
  }
}