Example #1
0
	// Read edgelist input file
	inline void readFile(char* filePath, nodeCollection* ncp){
		inputFileStream1.open(filePath);
			std::string line;
			std::string x, y, del;
			int maxValue, a, b;
			char oneLine[256];
			maxValue = 0;

			//To find max Value (to make dynamic array)
			if(inputFileStream1.is_open()){
				int lineNumber = 0;
				while(getline(inputFileStream1, line)){
					strcpy(oneLine,line.c_str());
					del = strtok(oneLine,"\t ");
					x = del;
					y = strtok(NULL,"\t ");
					lineNumber++;
					a = atoi(x.c_str());
					b = atoi(y.c_str());
					
					if ( a > b){
						if(a > maxValue){
							maxValue = a;}
					}
					else{
						if(b > maxValue){
							maxValue = b;}
					}
				}
			}
			else{
				std::cout<<"Error Occured!"<<std::endl;
			}

			//ncp->setAdjMat(maxValue);	//Make matrix
			ncp->setDegMat(maxValue);	//Make degMatrix
			inputFileStream1.seekg(0, inputFileStream1.beg);		//to read again
			inputFileStream1.close();
			inputFileStream2.open(filePath);
			if(inputFileStream2.is_open()){
				while(getline(inputFileStream2, line)){	
					strcpy(oneLine,line.c_str());
					del = strtok(oneLine,"\t ");
					x = del;
					y = strtok(NULL,"\t ");
					a = atoi(x.c_str());
					b = atoi(y.c_str());
					ncp->putNode(a, b);
					ncp->putNode(b, a);
					}
			}
			else{
				std::cout<<"Error Occured!"<<std::endl;
			}
			std::cout<<"####  FILE READ & SETUP FINISHED####"<<std::endl;
			inputFileStream2.close();
			
	}
Example #2
0
std::string MiscUtil::OpenFile(std::string name, std::ifstream& f)
{
#ifndef ABS_TOP_SRCDIR
    #error ABS_TOP_SRCDIR not defined!
#endif
#ifndef DATADIR
    #error ABS_TOP_SRCDIR not defined!
#endif
    std::string programDirFile;
    std::string absFile;
    std::string dataFile;
    # if defined(BOOST_FILESYSTEM_VERSION)
        BenzeneAssert (BOOST_FILESYSTEM_VERSION == 2 || BOOST_FILESYSTEM_VERSION == 3);
    #endif
    {
        path p = programDir / name;
        p.normalize();
        #if (defined (BOOST_FILESYSTEM_VERSION) && (BOOST_FILESYSTEM_VERSION == 3))
            programDirFile = p.string();
        #else
            programDirFile = p.native_file_string();
        #endif
        f.open(programDirFile.c_str());
        if (f.is_open())
            return programDirFile;
    }
    {
        path p = boost::filesystem::path(ABS_TOP_SRCDIR) / "share" / name;
        p.normalize();
        #if (defined (BOOST_FILESYSTEM_VERSION) && (BOOST_FILESYSTEM_VERSION == 3))
            absFile = p.string();
        #else
            absFile = p.native_file_string();
        #endif
        f.open(absFile.c_str());
        if (f.is_open())
            return absFile;
    }
    {
        path p = boost::filesystem::path(DATADIR) / name;
        p.normalize();
        #if (defined (BOOST_FILESYSTEM_VERSION) && (BOOST_FILESYSTEM_VERSION == 3))
            dataFile = p.string();
        #else
            dataFile = p.native_file_string();
        #endif
        f.open(dataFile.c_str());
        if (f.is_open())
            return dataFile;
    }
    throw BenzeneException() << "Could not find '" << name << "'. Tried \n"
                             << "\t'" << programDirFile << "' and\n"
                             << "\t'" << absFile << "' and\n"
                             << "\t'" << dataFile << "'.";
}
  //-------------------------------------------------------------------------//
  bool Material::Load(std::ifstream& ifs)
  {
    //-----------------------------------------------------------------------//
    // Throw assertion is file streams is not open.
    assert(ifs.is_open() && ifs.good());
    //-----------------------------------------------------------------------//

    //-----------------------------------------------------------------------//
    // If the file stream is not open return false.
    if(!ifs.is_open() || !ifs.good())
      return false;
    //-----------------------------------------------------------------------//

    //-----------------------------------------------------------------------//
    // This string will hold the label that describes some camera parameter.
    string strLabel;
    //-----------------------------------------------------------------------//

    //-----------------------------------------------------------------------//
    // This unsigned short will count the number of camera parameters read in
    // and will be used to verify that the correct number of parameters have 
    // been initialized.
    unsigned short usParameterCount = 0;
    //-----------------------------------------------------------------------//

    //-----------------------------------------------------------------------//
    // The for loop will read in data from the file stream and will set 
    // the objects data members accordingly.
    for(unsigned short i = 0; i < NUMBER_OF_MATERIAL_PARAMETERS; i++)
    {
      //---------------------------------------------------------------------//
      // Read in the label
      ifs >> strLabel;
      //---------------------------------------------------------------------//

      //---------------------------------------------------------------------//
      // Match the label to some predefined token and set the proper data member.
      float fR, fG, fB, fA;
      if(strLabel == DIFFUSE_COLOR_LABEL)
      {
        ifs >> fR;
        ifs >> fG;
        ifs >> fB;
        ifs >> fA;
        this->SetDiffuse(fR, fG, fB);
        usParameterCount++;
      }
      else if(strLabel == AMBIENT_FACTOR_LABEL)
Example #4
0
            /**
            * @brief Configures the block: defines the input file.
            * @param n The configuration parameters
            */
            virtual void _configure(const xml_node& n)
            {
                xml_node source = n.child("source");
                xml_node gates_node = n.child("gates");
                if( (!source)  || (!gates_node) )
                    throw std::runtime_error("TweetReader: missing parameter");
                std::string gates_s = gates_node.attribute("number").value();
                std::string type = source.attribute("type").value();
                std::string ip = source.attribute("ip").value();
                file_name = source.attribute("name").value();
                if(!type.length() || !file_name.length() || !gates_s.length())
                    throw std::runtime_error("TweetReader: missing attribute");
                if(type.compare("offline") != 0)
                    throw std::runtime_error("TweetReader: invalid type parameter");

                num_gates = atoi(gates_s.c_str());

                file.open(file_name);
                if(!file.is_open()) {
                    throw std::runtime_error("TweetReader: cannot open source file");
                }

                // Create and register the output gates
                m_outgate_ids = new int[num_gates];
                for(int i=0; i<num_gates; i++){
                    std::string ogate = outgate_basename + boost::lexical_cast<std::string>(i);
                    m_outgate_ids[i] = register_output_gate(ogate.c_str());
                }
            }
Example #5
0
/*Name: fOpen
//Purpose: Opens file with given filename
//Parameters: ifstream object, string filename, bool fail bit
//Returns: null
*/
void fOpen(std::ifstream& fin, string filename, bool& fail){
	fin.open(filename.c_str());
	if(!fin.is_open()){
		fail = 1;
		cerr << "File failed to open";
	}
}
// Unit test.
bool test_reverse_word(std::ifstream &file)
{
	if(!file.is_open())
	{
		throw; //file not open
	}

	std::string line;

	while(getline(file,line))
	{
		//make a deep copy...
		std::string expected = line + "";

		char* exp = &expected[0];
		char* actual = &line[0];

		reverse_words_quick_and_dirty(exp);
		reverse_words(actual);
		
		if(strcmp(actual,exp) != 0)
		{

			std::cout << "expected: " << exp << std::endl;
			std::cout << "actual  : " << actual << std::endl;
			std::cout << "Test Failed!" << std::endl;
			return false;
		}
	}

	std::cout << "Test Passed!" << std::endl;

	return true;
}
Example #7
0
	void Constants::setConstantsFromFile(std::ifstream & infile)
	{
		if(infile.is_open())
		{
			std::string input;
			while(std::getline(infile,input))
			{
				std::vector<float> params;
				if(input[0] == '#') continue;
				std::string commandName = input.substr(0,input.find_first_of(" "));

				input = input.substr(input.find_first_of(" ")+1,input.length());
				while(input.length() > 0)
				{
					int spaceloc = input.find_first_of(" \n\0");
					std::string param = input.substr(0,(spaceloc>=0)?spaceloc:input.length());
					if(input[0] == '#') ;
					if(spaceloc == -1)
						input = "";
					else
						input = input.substr(spaceloc+1,input.length());
					char * charParam = new char[input.size()+1];
					strcpy(charParam,param.c_str());
					float parameter = (float)atof(charParam);
					params.push_back(parameter);
				}
			
				if(commandName == "G_ACCEL")
				{
					Constants::getInstance()->gravity = params[0];
				}
			}
		}
	}
  bool closeEdgeFile(int iter_counter) {
 	 if (fin.is_open()) {
 		 fin.close();
 		 //logstream(LOG_INFO) << "close edge block-" << block_id << std::endl;
 	 }
 	 return true;
  }
Example #9
0
/*--------------------------------------------------------------------
						m_load_matches_from_stream
----------------------------------------------------------------------*/
bool CStereoOdometryEstimator::m_load_matches_from_stream(
		std::ifstream		& stream,
		vector<cv::DMatch>	& matches,
		vector<size_t>		& matches_ids )
{
	/* FORMAT
	- # of matches
		- match id
		- queryIdx
		- trainIdx
		- distance
	*/
	if( !stream.is_open() )
		return false;

	size_t num_matches, num_matches_id;
	stream.read( (char*)&num_matches, sizeof(size_t) );
	stream.read( (char*)&num_matches_id, sizeof(size_t) );
	matches.resize( num_matches );
	matches_ids.resize( num_matches_id );
	const bool add_ids = num_matches == num_matches_id;
	for( size_t m = 0; m < matches.size(); ++m )
	{
		if( add_ids ) stream.read( (char*)&(matches_ids[m]), sizeof(size_t) );
		stream.read( (char*)&(matches[m].queryIdx), sizeof(matches[m].queryIdx) );
		stream.read( (char*)&(matches[m].trainIdx), sizeof(matches[m].trainIdx) );
		stream.read( (char*)&(matches[m].distance), sizeof(matches[m].distance) );
		stream.read( (char*)&(matches[m].imgIdx), sizeof(matches[m].imgIdx) );
	} // end-for-matches

	return true;
} // end-loadMatchesFromStream
Example #10
0
void RigidBodyScene::deserialize( std::ifstream& inputstream )
{
  assert( inputstream.is_open() );

  // Load the state of each rigid body
  for( std::vector<RigidBody>::size_type i = 0; i < m_rbs.size(); ++i ) m_rbs[i].deserialize( inputstream );
}
//----------------------------------------------------------------------
bool KeyboardProfile::VInitialize( std::ifstream& fin, WkActionTranslatorPtr pActionTransl )
{
	auto pActiontranslator = pActionTransl.lock();
	auto pDevice = m_pKeyboard.lock();
	if( fin.is_open() && pActiontranslator && pDevice )
	{
		string temp;

		if( !InitializeGOID(fin) )
		{
			return false;
		}

		// Mapping button/action
		fin >> temp;
		while( temp != ";" )
		{
			if( StringUtilities::ToLower(temp) == "b" )
			{
				temp = MapButtonToAction( pDevice, pActiontranslator, fin );
			}
			else // Skip
			{
				do 
				{
					fin >> temp;
				} 
				while( temp != "b" && temp != ";" );
				return false;
			}
		}
		return true;
	}
Example #12
0
/** \brief Hide a file (or some other ifstream) in the loaded picture
 * It loads the streamsize to this->hundredPercentValue and the amount of finished bytes to this->doneBytes
 * \param &toHideFileStream std::ifstream the filestream whose contents should be hidden in the picture (should be opened binary)
 * \param &password const std::string the password (not used yet)
 * \throw SteganoException::ImgNotLoaded if no container file is loaded.
 * \throw SteganoException::Img2Small if the loaded image is too small to hide the given phrase
 * \throw SteganoException::FileStreamClosed if the specified fileStream is not opened
 */
void SteganoHide::hideFile(std::ifstream &toHideFileStream, const std::string &password) {
    if(!this->steganoImage.isValid()) {
        throw SteganoException::ImgNotLoaded();
    }

    // we need to divide it by 2 because in worst case every byte takes 2 pixel
    if(getFileStreamSizeInBytes(toHideFileStream) > (this->xResolution * this->yResolution) / 2) {
        throw SteganoException::Img2Small();
    }

    if(!toHideFileStream.is_open()) {
        throw SteganoException::FileStreamClosed();
    }

    this->origImageBackup = this->steganoImage;
    this->doneBytes = 0;
    // 2 * |imagePixel| because we normalize all pixels first and afterwards we reset it.
    this->hundredPercentValue = getFileStreamSizeInBytes(toHideFileStream) + 2 * this->pixelAmount;

    normalizeImage();
    unsigned int loopCount = 0;
    while(toHideFileStream.good()) {
        Pixel hidingPixel = calculateHidingPosition(loopCount);

        hideByteAtPixel(toHideFileStream.get(), hidingPixel);

        loopCount++;
        this->doneBytes++;
   //    std::cout << "byte" << std::endl;
    }

    drawFinishPixel(calculateHidingPosition(loopCount));
    resetNormalizedImage();
}
Example #13
0
void openfile(const char *filename, std::ifstream &infile){
    infile.open(filename);
    if (! infile.is_open()) {
        std::cout << "Error opening file:" << filename << std::endl;
        exit(1);
    }
}
Example #14
0
    bool InpNativeInfo::read_file(const std::string& file_name)
    {
        if(already_read)
            std::cout << "Warning: trying to substitute ninfo for already initiated object." 
                      << std::endl;
        already_read = true;

        if(inpfile.is_open())
        {
            std::cout << "Warning: trying to re-open file named " << file_name
                      << std::endl;
        }
        inpfile.open(file_name);
        bool read(false);
        
        while(!inpfile.eof())
        {
            std::string line;
            std::getline(inpfile, line);

            if(line.empty()) continue;
            if(line[0] == '\x2a') continue;

            if(eq_ignorecase(line.substr(0,20), "<<<< native_info_sim"))
            {
                read = true;
                std::string temp(line, 20);
                simN = std::stoi(temp);
                read_block(inpfile);
            }
        }
        return read;
    }
Example #15
0
		void open(std::ifstream& stream) const {
			stream.open(m_path.c_str(), std::ios::in|std::ios::binary);
			if (!stream.is_open()) {
				LOG4CXX_ERROR(m_logger, "Couldn't open file [" << m_path << "]");
				MR4C_THROW(std::logic_error, "Couldn't open file [" << m_path << "]");
			}
			stream.exceptions(std::ifstream::badbit);
		}
Example #16
0
// Ensure a filehandle is open
void assertFileOpen(std::ifstream& fh, const std::string& fn)
{
    if(!fh.is_open())
    {
        std::cerr << "Error: could not open " << fn << " for read\n";
        exit(EXIT_FAILURE);
    }
}
Example #17
0
    void
    close ()
    {
      if (file_in_.is_open ())
	{
	  file_in_.close ();
	}
    }
Example #18
0
bool OpenFile(std::ifstream & fileStream, const String & fileName
              , const char * _possibleLocations[])
{
  fileStream.open(fileName.c_str());

  int i=0;

  while (!fileStream.is_open()
         && _possibleLocations != NULL && _possibleLocations[ i ] != NULL)
  {
    fileStream.clear();
    fileStream.open((String(_possibleLocations[ i ]) + "/" + fileName).c_str());
    ++i;
  }

  return fileStream.is_open();
}
Example #19
0
bool openInputFile(std::ifstream& _inFile, std::string _path){
	_inFile.open(_path);

	if(!_inFile.is_open() || !_inFile.good())
			return false;

	return true;
}
Example #20
0
void printFileOpen(std::ifstream &fileStream) {
    if ( ! fileStream.is_open() ) {
        std::cout <<" Failed to open" << std::endl;
    }
    else {
        std::cout <<"Opened OK" << std::endl;
    }
}
Example #21
0
bool openInFile(const std::string &filename, std::ifstream &file){
  file.open(filename.c_str(),std::ifstream::in);
  if(!file.is_open()) {
    printf("Could not open input file %s", filename.c_str());
    return false;
  }
  return true;
}
Example #22
0
TimeIntegrator::TimeIntegrator(Eigen::VectorXd &napp, std::ifstream &dyn_id, double &mass)
{
    _napp = napp;

    std::string line;
    if (dyn_id.is_open())
    {
        std::vector<double> F_std, T_std;
        while (dyn_id.good())
        {
            while(std::getline(dyn_id,line,'\n'))
            {
                // Ignore blank lines in the begining of the file (if any)
                if(line.empty()) continue;
                // Trim white space from the beginning of the string
                line.erase(line.begin(), std::find_if(line.begin(), line.end(), std::not1(std::ptr_fun<int, int>(isspace))));
                // If line starts with /, //, #, * and %, ignore it
                if(line[0] == '#' || line[0]=='/' || line[0]=='%' || line[0]=='*') continue;

                // Read data
                // Note: automatically rules out strings and does not convert them. No need for checking
                std::vector<double> inputs;
                std::istringstream sline(line);
                std::copy( std::istream_iterator<double>(sline),std::istream_iterator<double>(),std::back_inserter(inputs));

                // Build Piezoelectric Matrix
                if (inputs.size()==2)
                {
                    T_std.push_back(inputs[0]);
                    F_std.push_back(inputs[1]);
                }
            }
        }
        // Determine nstep, dt, F1
        // Map F1 using temp
        Eigen::Map<Eigen::VectorXd> Acc_temp(F_std.data(),F_std.size());
        F1=Acc_temp*mass; // accecelaration into mass
        _nstep = T_std.size();
        for (unsigned int i=0; i<T_std.size(); ++i)
        {
            if (T_std[i+1]>T_std[i])
            {
                _dt = T_std[i+1]-T_std[i];
                break;
            }
            else
            {
                // Turn this off for GUI mode
//                throw std::invalid_argument("Could not determine time-step size");
            }
        }
    }
    else
    {
        // Turn this off for GUI mode
//        throw std::invalid_argument("Could not open the file!");
    }
}
Example #23
0
  //-------------------------------------------------------------------------//
  bool Mesh::Load(std::ifstream& ifs)
  {
    bool bReturnValue = false;

    //-----------------------------------------------------------------------//
    // Ensure the file stream passed into this method is open
    assert(ifs.is_open());
    if(ifs.is_open())
    {
      ifs >> mulNumberOfFaces;
      ifs >> mulNumberOfVertices;
      ifs >> mulNumberOfIndices;

      unsigned long ulArrayIndex = 0UL;
      unsigned long ulIndicesIndex = 0UL;

      //---------------------------------------------------------------------//
      if(this->mpIndexArray != NULL)
        delete [] this->mpIndexArray;

      this->mpIndexArray = new unsigned long[mulNumberOfIndices];
      //---------------------------------------------------------------------//

      //---------------------------------------------------------------------//
      // Clear vertex data is any exist and create a new buffer for this mesh
      if(this->mpVertexArray != NULL)
        delete [] this->mpVertexArray;

      this->mpVertexArray = new Vertex[mulNumberOfVertices];
      //---------------------------------------------------------------------//

      //---------------------------------------------------------------------//
      while(!ifs.eof() && ((ulIndicesIndex < mulNumberOfIndices) || (ulArrayIndex < mulNumberOfVertices)))
      {
        string strLabel;
        ifs >> strLabel;
        if(strLabel == "Loc")
        {
          float fX, fY, fZ;
          ifs >> fX;
          ifs >> fY;
          ifs >> fZ;
          Object::Position(fX, fY, fZ);
        }
        else if(strLabel == "v")
 // This closes the file which was being parsed, if there is one open.
 inline void RestrictedXmlParser::CloseFile()
 {
   if( xmlFileStream.is_open() )
   {
     xmlFileStream.close();
   }
   xmlFileStream.clear();
   xmlStream = &xmlStringStream;
 }
Example #25
0
File: main.cpp Project: dlxgit/OOP
bool IsFileNameCorrect(const std::ifstream & inputFile)
{
	if (inputFile.is_open())
	{
		return true;
	}
	std::cout << "inputFile name is incorrect" << std::endl;
	return false;
}
Example #26
0
inline lf_file::lf_file(std::string fname):
post_header_pos(0)
{
  f.open(fname.c_str(), std::ifstream::in);
  if (!f.is_open()) {
    throw std::runtime_error("Could not open file.\n ");
  }
  parse_header();
}
  inline bool
  hash_commented_file_reader::file_is_open()
  const
  // this returns true if the file to be read was successfully opened.
  {

    return input_file.is_open();

  }
Example #28
0
bool const
file_handler<
    std::string,
    std::ifstream>::get_data(
        std::string const &key,
        std::ifstream &value) const
{
    value.open(key.c_str(), std::ios_base::binary);
    return value.is_open();
}
Example #29
0
void
OpenIFile(std::ifstream& fs, const char* filenm)
{
  using namespace std;

  fs.open(filenm, ios::in);
  if (!fs.is_open() || fs.fail()) {
    DIAG_Throw("Cannot open file '" << filenm << "'");
  }
}
Example #30
0
void initializeInstructionMemory(std::ifstream &fp) {
	std::string line;
	std::string text;
	if (fp.is_open()) {
		while ( getline(fp,line) ) {
			text << line << '\n';
		}
	fp.close();
	}
}