int
GA3DBinaryStringGenome::read(std::istream & is)
{
  static char c;
  unsigned int i=0, j=0, k=0;
  do{
    is >> c;
    if(isdigit(c)){
      gene(i++, j, k, ((c == '0') ? 0 : 1));
      if(i >= nx){
	i=0;
	j++;
      }
      if(j >= ny){
	j=0;
	k++;
      }
    }
  } while(!is.fail() && !is.eof() && k < nz);

  _evaluated = gaFalse;

  if(is.eof() && 
     ((k < nz) ||		// didn't get some lines
      (j < ny && j != 0) ||	// didn't get some lines
      (i < nx && i != 0))){	// didn't get some lines
    GAErr(GA_LOC, className(), "read", gaErrUnexpectedEOF);
    is.clear(std::ios::badbit | is.rdstate());
    return 1;
  }

  return 0;
}
Exemple #2
0
std::string ImageCoder::storeStreamToTempFile(std::istream & stream)
{
	std::string fileName;
	{
		char fileNameBuffer[L_tmpnam];
		char * result = tmpnam(fileNameBuffer);
		if (result == nullptr)
			return fileName;	// empty file name indicates a problem ...
		fileName.assign(result);
	}

	std::ofstream file(fileName, std::ofstream::binary);
	if (file.fail())
		std::runtime_error("failed to create temp file: '" + fileName + "'");

	try
	{
		file << stream.rdbuf();
		if (file.fail() || stream.fail())
			std::runtime_error("failed to write to temp file: '" + fileName + "'");
	}
	catch (const std::iostream::failure &)
	{
		std::runtime_error("failed to write to temp file: '" + fileName + "', caught failure");
	}
	return fileName;
}
Exemple #3
0
static uint8_t readHexByte(std::istream & s)
{
    std::istream::sentry sentry(s, true);
    if (sentry)
    {
        char c1 = 0, c2 = 0;
        s.get(c1);
        s.get(c2);

        if (s.fail())
        {
            if (s.eof())
            {
                throw std::runtime_error("Unexpected end of line.");
            }
            else
            {
                throw std::runtime_error("Failed to read hex digit.");
            }
        }

        int v1 = hexDigitValue(c1);
        int v2 = hexDigitValue(c2);

        if (v1 < 0 || v2 < 0)
        {
            throw std::runtime_error("Invalid hex digit.");
        }

        return v1 * 16 + v2;
    }
    return 0;
}
Exemple #4
0
void process(const std::string& fname, std::istream& sin = std::cin,
      std::ostream& sout = std::cout)
   {
   // Communication system
   libcomm::commsys<S, C> *system = libcomm::loadfromfile<
         libcomm::commsys<S, C> >(fname);
   std::cerr << system->description() << std::endl;
   // Initialize system
   libbase::randgen r;
   r.seed(0);
   system->seedfrom(r);
   // Repeat until end of stream
   for (int i=0; !sin.eof(); i++)
      {
      // skip any comments
      libbase::eatcomments(sin);
      // attempt to read a block of the required size
      C<int> source(system->input_block_size());
      source.serialize(sin);
      // stop here if something went wrong (e.g. incomplete block)
      if (sin.fail())
         {
         std::cerr << "Failed to read block " << i << std::endl;
         break;
         }
      // encode block and push to output stream
      C<S> transmitted = system->encode_path(source);
      transmitted.serialize(sout, '\n');
      // skip any trailing whitespace (before check for EOF)
      libbase::eatwhite(sin);
      }
   // Destroy what was created on the heap
   delete system;
   }
Exemple #5
0
OSG_USING_NAMESPACE

bool sRead(std::istream &file,
           void         *value,
           Int32         size,
           bool          swapit)
{
    Char8 buffer[4];

    if(size > 4)
        return false;

    if(swapit)
    {
        file.read(buffer, size);

        for(Int32 i = 0; i < size; i++)
        {
            static_cast<Char8 *>(value)[i] = buffer[size - i - 1];
        }
    }
    else
    {
        file.read (static_cast<Char8 *>(value), size);
    }

    bool failed = file.fail();
    return !failed;
}
template<class T> void WavFileInputSoundStream::read(std::istream & is, T & t)
{
	is.read(reinterpret_cast<char *>(&t), sizeof(T));
	if(is.eof()) throw std::string("EOF");
	if(is.fail()) throw std::string("FAIL");
	if(is.bad()) throw std::string("BAD");
}
std::string ReadValueStr(std::string prompt /*= std::string()*/, std::istream& in /*= std::cin*/, std::ostream* out /*= &std::cout*/)
{
    if (out)
        (*out) << prompt;

    std::string input;
    bool success = false;

    while (!success)
    {
        std::getline(in, input);

        if (in.fail())
        {
            if (in.eof())
            {
                in.clear();
                throw EOFCharacterValue();
            }
            else
            {
                in.clear();
                if (out)
                    (*out) << "Invalid value. Please try again." << std::endl;
                else
                    throw InvalidValue("ReadValue: Invalid value found with no out stream.");
                continue;
            }
        }
        success = true;
    }

    return input;
}
Exemple #8
0
void IndexStreamBuffer::update(std::istream& data)
{
	std::size_t size = count * static_cast<std::size_t>(format);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, GL_STREAM_DRAW);
	void* map = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY);
	if (map == nullptr) {
		glGetError();
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		throw Error("Failed to map index buffer.", __FILE__, __LINE__);
	}
	data.read(reinterpret_cast<char*>(map), size);
	if (data.fail() || data.gcount() != static_cast<std::streamsize>(size)) {
		glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		throw IOException("Failed to read index buffer from stream.");
	}
	if (!glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER)) {
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		throw Error("Failed to unmap index buffer.", __FILE__, __LINE__);
	}
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	if (glGetError() != GL_NO_ERROR) {
		throw Error("Failed to update index buffer.", __FILE__, __LINE__);
	}
}
OpenRAVE::InterfaceBasePtr CreateInterfaceValidated(OpenRAVE::InterfaceType type,
    std::string const &interface_name, std::istream &sinput, OpenRAVE::EnvironmentBasePtr env)
{

    if (type == OpenRAVE::PT_Sensor && interface_name == "bhtactilesensor") {
        std::string node_name, owd_namespace, robot_name, link_prefix;
        sinput >> node_name >> owd_namespace >> robot_name >> link_prefix;

        // Initialize the ROS node.
        RAVELOG_DEBUG("name = %s  namespace = %s\n", node_name.c_str(), owd_namespace.c_str());
        if (sinput.fail()) {
            RAVELOG_ERROR("BHTactileSensor is missing the node_name, owd_namespace, robot_name, or link_prefix parameter(s).\n");
            return OpenRAVE::InterfaceBasePtr();
        }

        if (!ros::isInitialized()) {
            int argc = 0;
            ros::init(argc, NULL, node_name, ros::init_options::AnonymousName);
            RAVELOG_DEBUG("Starting ROS node '%s'.\n", node_name.c_str());
        } else {
            RAVELOG_DEBUG("Using existing ROS node '%s'\n", ros::this_node::getName().c_str());
        }

        OpenRAVE::RobotBasePtr robot = env->GetRobot(robot_name);
        if (!robot) {
            throw OPENRAVE_EXCEPTION_FORMAT("There is no robot named '%s'.",
                                            robot_name.c_str(), OpenRAVE::ORE_InvalidArguments);
        }
        return boost::make_shared<BHTactileSensor>(env, robot, owd_namespace, link_prefix);
    } else {
std::streamsize fullread(
	std::istream& istr,
	char* buf,
	std::streamsize requested)
{
	std::streamsize got;
	std::streamsize total = 0;

	istr.read(buf, requested);	 /*Flawfinder: ignore*/
	got = istr.gcount();
	total += got;
	while(got && total < requested)
	{
		if(istr.fail())
		{
			// If bad is true, not much we can doo -- it implies loss
			// of stream integrity. Bail in that case, and otherwise
			// clear and attempt to continue.
			if(istr.bad()) return total;
			istr.clear();
		}
		istr.read(buf + total, requested - total);	 /*Flawfinder: ignore*/
		got = istr.gcount();
		total += got;
	}
	return total;
}
Exemple #11
0
void getAsString(std::string& out, std::istream& is)
{
	std::getline(is, out, '\0');
	if (is.fail()) {
        throw ExceptionStack("getAsString", __FILE__, __LINE__);
    }
}
bool VehicleStateBasicLux::deserialize(std::istream& is, const IbeoDataHeader& dh)
{
	const std::istream::pos_type startPos = is.tellg();

	lock();

	ibeo::readLE(is, m_timestamp);
	ibeo::readLE(is, m_scanNumber);
	ibeo::readLE(is, m_errorFlags);
	ibeo::readLE(is, m_longitudinalVelocity);
	ibeo::readLE(is, m_steeringWheeAngle);
	ibeo::readLE(is, m_wheelAngle);
	ibeo::readLE(is, m_reserved0);

	ibeo::readLE(is, m_xPos);
	ibeo::readLE(is, m_yPos);
	ibeo::readLE(is, m_courseAngle);

	ibeo::readLE(is, m_timeDiff);
	ibeo::readLE(is, m_xDiff);
	ibeo::readLE(is, m_yDiff);
	ibeo::readLE(is, m_yaw);

	ibeo::readLE(is, m_reserved1);
	ibeo::readLE(is, m_currentYawRate);
	ibeo::readLE(is, m_reserved2);

	unlock();

	return !is.fail()
	       && ((is.tellg() - startPos) == this->getSerializedSize())
	       && this->getSerializedSize() == dh.getMessageSize();}
int32_t skipVolume(std::istream& in, bool binary, size_t totalSize)
{
  int32_t err = 0;
  if (binary == true)
  {
    std::istream::pos_type pos = in.tellg();
    qint64 newPos = totalSize * sizeof(T) + 1;
    in.seekg(newPos, std::ios_base::cur); // Move relative to the current position
    pos = in.tellg();
    if (in.fail())
    {
      // check if the position to jump to is past the end of the file
      return -1;
    }
  }
  else
  {
    T tmp;
    for (size_t z = 0; z < totalSize; ++z)
    {
      in >> tmp;
    }
  }
  return err;
}
Exemple #14
0
/**
 * 手順の読み込み
 */
bool CsaReader::readMoves(std::istream& is, Record& record) {
  char line[LINE_BUFFER_SIZE];
  Move move;

  while (true) {
    is.getline(line, sizeof(line));
    if (is.eof()) {
      return true;
    }
    if (is.fail()) {
      Loggers::warning << "file io error: " << __FILE__ << "(" << __LINE__ << ")";
      return false;
    }
    if (readComment_(line) || readCommand_(line) || readTime_(line)) {
      continue;
    }
    if (!readMove(line, record.getBoard(), move)) {
      Loggers::warning << "invalid move format: " << __FILE__ << "(" << __LINE__ << ")";
      Loggers::warning << "> " << line;
      return false;
    }
    if (!record.makeMove(move)) {
      Loggers::warning << "invalid move: " << __FILE__ << "(" << __LINE__ << ")";
      Loggers::warning << "> " << line;
      return false;
    }
  }
}
Exemple #15
0
/**
 * 局面の読み込み
 */
bool CsaReader::readBoard_(std::istream& is, Board& board, RecordInfo* info/* = nullptr*/) {
  char line[LINE_BUFFER_SIZE];

  board.init();

  while (true) {
    is.getline(line, sizeof(line));
    if (is.eof()) {
      break;
    }
    if (is.fail()) {
      Loggers::warning << "file io error: " << __FILE__ << "(" << __LINE__ << ")";
      return false;
    }
    if (!readBoard_(line, board, info)) {
      Loggers::warning << "invalid board format: " << __FILE__ << "(" << __LINE__ << ")";
      return false;
    }
    if (line[0] == '+' || line[0] == '-') {
      break;
    }
  }

  assert(board.getBKingSquare() != Square::Invalid);
  assert(board.getWKingSquare() != Square::Invalid);

  return true;
}
Exemple #16
0
void reader_utility::ignoreCommentLines(std::istream& stream, const std::string& lineHead)
{
    if (stream.fail() || stream.eof()) return;

    std::istream::pos_type pos = stream.tellg();

    std::string peekStr;
    while (stream >> peekStr) {
        int strSize = lineHead.size();
        bool commentFound = (static_cast<int>(peekStr.size()) >= strSize &&
                             peekStr.substr(0, strSize) == lineHead);
        if (commentFound) {
            ignoreLine(stream);
            pos = stream.tellg();
        }
        else {
            stream.seekg(pos, std::ios_base::beg);
            return;
        }
    }

    if (stream.eof()) {
        stream.clear();
        stream.seekg(pos, std::ios_base::beg);
    }
}
Exemple #17
0
int
pcl::gpu::people::trees::loadTree ( std::istream&       is,
                                    std::vector<Node>&  tree,
                                    std::vector<Label>& leaves )
{
  // load the depth
  int maxDepth;
  is >> maxDepth;
  int numNodes  = (1 << maxDepth) - 1; //pow(2.0,maxDepth)-1;
  int numLeaves = (1 << maxDepth);    //pow(2.0,maxDepth);

  // alloc
  tree.resize(numNodes);
  leaves.resize(numLeaves);

  // read
  for(int ni = 0; ni < numNodes; ++ni)
    is >> tree[ni];

  // the int is necessary.. otherwise it will format it as unsigned char
  for(int li = 0; li < numLeaves; ++li) 
  {
      int l; is >> l; leaves[li] = l; 
  }

  // Check loading of the tree in terminal
  PCL_DEBUG("[pcl::gpu::people::trees::loadTree] : (D) : loaded %d nodes, %d leaves and depth %d\n", numNodes, numLeaves, maxDepth);

  if( is.fail() )
     throw std::runtime_error(std::string("(E) malformed *.tree stream") );
  return maxDepth;
}
Exemple #18
0
void IndexStreamBuffer::update(
	std::istream& data, std::size_t start, std::size_t count
) {
	std::size_t size = count * static_cast<std::size_t>(format);
	std::size_t offset = start * static_cast<std::size_t>(format);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ID);
	void* map = glMapBufferRange(
		GL_ELEMENT_ARRAY_BUFFER, offset, size,
		GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT
	);
	if (map == nullptr) {
		glGetError();
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		throw Error("Failed to map index buffer.", __FILE__, __LINE__);
	}
	data.read(reinterpret_cast<char*>(map), size);
	if (data.fail() || data.gcount() != static_cast<std::streamsize>(size)) {
		glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		throw IOException("Failed to read index buffer from stream.");
	}
	if (!glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER)) {
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		throw Error("Failed to unmap index buffer.", __FILE__, __LINE__);
	}
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	if (glGetError() != GL_NO_ERROR) {
		throw Error("Failed to update index buffer.", __FILE__, __LINE__);
	}
}
Exemple #19
0
    void Storage::loadDataFromStream(ContainerType& container, std::istream& stream)
    {
        std::string line;
        while (!stream.eof() && !stream.fail())
        {
            std::getline( stream, line );
            if (!line.empty() && *line.rbegin() == '\r')
              line.resize(line.size() - 1);

            if (!line.empty())
            {
                line = mEncoder->getUtf8(line);

                size_t tab_pos = line.find('\t');
                if (tab_pos != std::string::npos && tab_pos > 0 && tab_pos < line.size() - 1)
                {
                    std::string key = line.substr(0, tab_pos);
                    std::string value = line.substr(tab_pos + 1);

                    if (!key.empty() && !value.empty())
                        container.insert(std::make_pair(key, value));
                }
            }
        }
    }
Exemple #20
0
bool ObjectListEcu::deserialize(std::istream& is, const IbeoDataHeader& dh)
{
	const std::istream::pos_type startPos = is.tellg();

	lock();

	ibeo::readBE(is, m_scanStartTimestamp);

	{
		UINT16 nbOfObjects;
		ibeo::readBE(is, nbOfObjects);

		if (nbOfObjects > ObjectListEcu::maxEcuObjects) {
			logWarning << "Object list with too many objects (" << nbOfObjects << ") received."
			" List will be ignored." << std::endl;
			return false;
		}

		if (m_objects.size() != nbOfObjects)
			m_objects.resize(nbOfObjects);
	}

	std::vector<ObjectEcu>::iterator objIter = m_objects.begin();
	for (; objIter != m_objects.end(); ++objIter) {
		objIter->deserialize(is);
	}

	unlock();
	return !is.fail()
	       && ((is.tellg() - startPos) == this->getSerializedSize())
	       && this->getSerializedSize() == dh.getMessageSize();
}
Exemple #21
0
msdata::msdata(std::istream& in, size_t fsize) : loaded_( false )
{
    static_assert(sizeof( detail::msdata ) == msdata::block_size
                  , "struct 'msdata' not alinged to 256 octets, check declaration.");

    int16_t scan = 0;
    while ( ( fsize - in.tellg() ) >= block_size ) {
        //auto pos = in.tellg();
        auto d = std::make_shared< detail::msdata >();
        in.read( reinterpret_cast<char *>(d.get()), block_size );
        //const detail::msdata * pdata = d.get();
        if ( in.fail() )
            return;
        if ( (d->flags & 0x0f) != record_type_code ) 
            return;

        if ( scan == 0 ) // 1-orign value
            scan = d->scan;

        if ( scan != d->scan )
            return;

        data_.push_back( d );
    }
}
Exemple #22
0
/**
 * local functions
 */
int deserialize_string(std::istream& istr, std::string& value, S32 max_bytes)
{
	char c = istr.get();
	if(istr.fail())
	{
		// No data in stream, bail out but mention the character we
		// grabbed.
		return LLSDParser::PARSE_FAILURE;
	}

	int rv = LLSDParser::PARSE_FAILURE;
	switch(c)
	{
	case '\'':
	case '"':
		rv = deserialize_string_delim(istr, value, c);
		break;
	case 's':
		// technically, less than max_bytes, but this is just meant to
		// catch egregious protocol errors. parse errors will be
		// caught in the case of incorrect counts.
		rv = deserialize_string_raw(istr, value, max_bytes);
		break;
	default:
		break;
	}
	if(LLSDParser::PARSE_FAILURE == rv) return rv;
	return rv + 1; // account for the character grabbed at the top.
}
Exemple #23
0
  void ClusterImpl::read(std::istream& in)
  {
    log_debug1("read");

    // read first offset, which specifies, how many offsets we need to read
    size_type offset;
    in.read(reinterpret_cast<char*>(&offset), sizeof(offset));
    if (in.fail())
      return;

    offset = fromLittleEndian(&offset);

    size_type n = offset / 4;
    size_type a = offset;

    log_debug1("first offset is " << offset << " n=" << n << " a=" << a);

    // read offsets
    offsets.clear();
    data.clear();
    offsets.reserve(n);
    offsets.push_back(0);
    while (--n)
    {
      in.read(reinterpret_cast<char*>(&offset), sizeof(offset));
      if (in.fail())
      {
        log_debug1("fail at " << n);
        return;
      }
      offset = fromLittleEndian(&offset);
      log_debug1("offset=" << offset << '(' << offset-a << ')');
      offsets.push_back(offset - a);
    }

    // last offset points past the end of the cluster, so we know now, how may bytes to read
    if (offsets.size() > 1)
    {
      n = offsets.back() - offsets.front();
      data.resize(n);
      if (n > 0)
      {
        log_debug1("read " << n << " bytes of data");
        in.read(&(data[0]), n);
      }
    }
  }
Exemple #24
0
ossimErrorCode ossimRpfFrame::populateReplaceUpdateTable(std::istream& in)
{
   ossimErrorCode result = ossimErrorCodes::OSSIM_OK;
   
   const ossimRpfLocationSection* location = theHeader->getLocationSection();

   if( location )
   {
      if ( location->hasComponent(OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER) )
      {
         ossimRpfComponentLocationRecord component;
         if( location->getComponent(OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER, component) )
         {
            ossimRefPtr<ossimRpfReplaceUpdateSectionSubheader> hdr =
               new ossimRpfReplaceUpdateSectionSubheader();
            
            in.seekg(component.m_componentLocation, ios::beg);
            
            if( hdr->parseStream( in, theHeader->getByteOrder() ) == ossimErrorCodes::OSSIM_OK )
            {
               ossim_uint16 count = hdr->getNumberOfRecords();
               if ( count )
               {
                  if ( theReplaceUpdateTable.valid() )
                  {
                     theReplaceUpdateTable->clear();
                  }
                  else
                  {
                     theReplaceUpdateTable = new ossimRpfReplaceUpdateTable();
                  }
                  ossimRpfReplaceUpdateRecord record;
                  for ( ossim_uint16 i = 0; i < count; ++i )
                  {
                     if ( record.parseStream(in) == ossimErrorCodes::OSSIM_OK )
                     {
                        theReplaceUpdateTable->addRecord( record );
                     }
                     else
                     {
                        break;
                     }
                  }
               }
               
            }
         }  
      }
   }

   if ( in.fail() )
   {
      theReplaceUpdateTable = 0;
      result = ossimErrorCodes::OSSIM_ERROR;
   }

   return result;

} // End: ossimRpfFrame::populateReplaceUpdateTable(std::istream& in)
Exemple #25
0
  void GRCsim::execute_vectors(std::istream &vf)
  {
    string line;

    // Enumerate the inputs to be read from the vector file

    vector<SignalSymbol*> inputs;

    for ( SymbolTable::const_iterator isym = sigs->begin() ;
  	isym != sigs->end() ; isym++ ) {
      SignalSymbol *ss = dynamic_cast<SignalSymbol*>(*isym);
      assert(ss);
      if ( ss->name != "tick" && (ss->kind == SignalSymbol::Input ||
  				ss->kind == SignalSymbol::Inputoutput ) ) {
        if ( debug & debugVectors ) std::cout << ss->name << '\n';
        inputs.push_back(ss);
      }
    }

    init();

    int ntick = 0;
    ISFinal = false;
    do {
      getline(vf, line);
      if (vf.fail()) break;

      if ( line.size() < inputs.size() ) {
        cerr << "Not enough inputs (" << line.size() << '<' << inputs.size()
  	   << ") in test vector file\n"
             << "Got \"" << line << "\"\n";
        exit(-2);
      }

      clear_inputs();
      string::const_iterator j = line.begin();
      for ( vector<SignalSymbol*>::const_iterator i = inputs.begin() ;
  	  i != inputs.end() ; j++ )
  	if ((*j) != ' ') {
            if ((*j) == '1')
              signals[*i] = 1;
            else if ((*j) == '0')
    	    signals[*i] = 0;
            else{ 
              signals[*i] = -1; //unknown
              ternary = true; //FIXME: may be wrong
            }
            i++;
  	}
      
      if (debug) cerr << "######## TICK " << ntick <<" TV :"<<line<< endl;
      char buf[5];
      sprintf(buf, "%4d ", ntick);
      outf << buf;
      ntick++;

      dotick();
    } while (!ISFinal);
  }
Exemple #26
0
/*------------------------------------------------------------------------------
 *  Add a configuration line
 *----------------------------------------------------------------------------*/
void
Config :: read (    std::istream  & is  )               throw ( Exception )
{
    char            line[LINE_SIZE];
    unsigned int    num;

    for ( num = 0; !is.fail() && !is.eof(); ++num ) {
        is.getline( line, LINE_SIZE);
        if ( is.eof() ) {
            break;
        } else if ( is.fail() ) {
            throw Exception( __FILE__, __LINE__, "line too long", num);
        }

        addLine( line);
    }
}
void ProductParser::parseCommonProduct(std::istream& is, 
				       bool& error,
				       string& errorMsg,
				       int& lineno)
  
{
  lineno++;
  string myline;
  getline(is, myline);
  myline = trim(myline);
  if(myline.size() == 0){
    error = true;
    errorMsg = "Unable to find a product name";
    return;
  }
  prodName_ = myline;
  
  lineno++;
  getline(is, myline);
  if(is.fail()){
    error = true;
    errorMsg = "Expected another line with the price";
    return;    
  }
  stringstream ss1(myline);
  ss1 >> price_;
  if( ss1.fail() ){
    error = true;
    errorMsg = "Unable to read price";
    return;
  }

  lineno++;
  getline(is, myline);
  if(is.fail()){
    error = true;
    errorMsg = "Expected another line with the quantity";
    return;    
  }
  stringstream ss2(myline);
  ss2 >> qty_;
  if( ss2.fail() ){
    error = true;
    errorMsg = "Unable to read quantity";
  }
}
  // http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
  // Nothing fancy here. We parse name/value pairs based on the '=' delimiter
  // The Java parser is much more versatile.
  void PropertiesConfiguration::parseLine(std::istream &input, size_t lineno) {
    ASSERT(!input.fail());
    if(input.fail())
      throw std::runtime_error("Should I shit or go blind???");

    std::string line;
    if (getline(input, line))
      {
	// This trim is needed to properly catch comments
	trimWhitespace(line);
	if(line.empty() || line[0] == '#')
	  return;

	static const char delim = '=';
	const size_t pos = line.find(delim, 0);

        ASSERT(pos != String::npos);
        if(pos == String::npos) {
          std::ostringstream ss;
          ss << "parseLine: delimiter not found (line: " << lineno << ")";
          // std::clog << ss.str() << std::endl;
          throw IllegalArgumentException(ss.str());
        }

	std::string key = line.substr(0, pos);
	std::string value = line.substr(pos + 1, line.size());

        // Keys must be present
	trimWhitespace(key);
        ASSERT(!key.empty());
        if(key.empty()) {                    
          std::ostringstream ss;
          ss << "parseLine: property key is not valid (line: " << lineno << ")";
          // std::clog << ss.str() << std::endl;
          throw IllegalArgumentException(ss.str());
        }

        // Value is optional, but will likely result in an exception during retrieval.
        // String *will not* throw on getString(...); but Bool and Int *will*
        // throw when using getBool(...) or getInt(...).
	trimWhitespace(value);	
	ASSERT(!value.empty());

        setString(key, value);
      }
  }
Exemple #29
0
bool YumemiArchive_Base::DeserializeList(std::istream &is, uint32_t list_count, uint32_t filesize, EntryList &list)
{
  for(uint16_t i = 0; i < list_count; ++i) {
    Entry entry;
    uint16_t magic;
    char     padding[8];
    is.read((char *)&magic, 2);
    if(is.fail()) return false;
    is.read((char *)&entry.key, 1);
    if(is.fail()) return false;
    is.read(entry.name, 13);
    if(is.fail()) return false;
    is.read((char *)&entry.compsize, 2);
    if(is.fail()) return false;
    is.read((char *)&entry.origsize, 2);
    if(is.fail()) return false;
    is.read((char *)&entry.offset, 4);
    if(is.fail()) return false;
    is.read(padding, 8);
    if(is.fail()) return false;

    if(magic == 0) break;

    if(magic != 0x9595 && magic != 0xF388) return false;
    if(entry.offset >= filesize) return false;
    if((uint32_t)filesize - entry.offset < entry.compsize) return false;
    if(!ValidateName(entry.name)) return false;
    list.push_back(entry);
  }
  return true;
}
uint readLevel(std::istream & iss)
{
  uint perftLevel = readValue<uint>(iss);
  if (iss.fail()) {
    std::cout << "Invalid perft level\n";
    return 0;
  }
  return perftLevel;
}