Example #1
0
R_Tree::R_Tree(std::ifstream& in)
{
  error_code = 0;
  tree = 0;
  reverse_bytes = false;
  f_offset = in.tellg();
  
  const unsigned int header_size = 48;
  char* header_bytes = new char[header_size];

  in.read(header_bytes, header_size);
  if(!in.good()){
    error_code = 1;
    std::cerr << "R_Tree Unable to read in index from file " << std::endl;
    delete []header_bytes;
    return;
  }
  
  header_magic = *(unsigned int*)header_bytes;
  if(header_magic != R_TREE_MAGIC){
    reverse_bytes = true;
    header_magic = __builtin_bswap32(header_magic);
  }
  if(header_magic != R_TREE_MAGIC){
    std::cerr << "R_Tree Unable to find correct magic got: " << header_magic
	      << "Wanted : " << R_TREE_MAGIC << std::endl;
    error_code = 2;
    delete []header_bytes;
    return;
  }
  
  ByteReader br(header_bytes, header_size, reverse_bytes);
  blockSize = br.ui(4);
  itemCount = br.ul(8);
  startChromIx = br.ui(16);
  startBase = br.ui(20);
  endChromIx = br.ui(24);
  endBase = br.ui(28);
  endFileOffset = br.ul(32);
  itemsPerSlot = br.ui(40);
  reserved = br.ui(44);
  
  delete []header_bytes;
  tree = new R_TreeNode(in, 0, in.tellg(), reverse_bytes);
}
Example #2
0
void
Producer::populateSegments(std::ifstream& ifs)
{
  BOOST_ASSERT(m_segments.size() == 0);

  // calculate how many segments are needed
  std::streampos begin, end;
  begin = ifs.tellg();
  ifs.seekg(0, std::ios::end);
  end = ifs.tellg();

  int num_segments = (end-begin) / m_maxSegmentSize;
  if ((end-begin) % m_maxSegmentSize != 0)
    num_segments++;

  std::cout << "Size of the file: " << (end-begin) << " bytes." << std::endl;
  std::cout << "Maximum size of a segment: " << m_maxSegmentSize << " bytes." << std::endl;
  std::cout << "Number of segments: " << num_segments << std::endl;

  std::vector<uint8_t> buffer(m_maxSegmentSize);
  ifs.seekg(0, std::ios::beg);
  for (int i = 0; i < (end-begin) / m_maxSegmentSize; ++i) {
    ifs.read(reinterpret_cast<char*>(buffer.data()), m_maxSegmentSize);
    auto data = make_shared<Data>(Name(m_prefix).appendSegment(i));
    data->setFreshnessPeriod(m_freshnessPeriod);
    data->setContent(&buffer[0], m_maxSegmentSize);
    //std::cout << *data << std::endl;
    m_segments.push_back(data);
  }

  if ((end-begin) % m_maxSegmentSize != 0) {
    ifs.read(reinterpret_cast<char*>(buffer.data()), (end-begin) % m_maxSegmentSize);
    auto data = make_shared<Data>(Name(m_prefix).appendSegment(m_segments.size()));
    data->setFreshnessPeriod(m_freshnessPeriod);
    data->setContent(&buffer[0], (end-begin) % m_maxSegmentSize);
    //std::cout << *data << std::endl;
    m_segments.push_back(data);
  }

  auto finalBlockId = name::Component::fromSegment(m_segments.size() - 1);
  for (const auto& data : m_segments) {
    data->setFinalBlockId(finalBlockId);
    m_keyChain.sign(*data, m_signingInfo);
  }
}
Example #3
0
	unsigned long getFileLength(std::ifstream& file)
	{
		if(!file.good()) return 0;

		file.seekg(0, std::ios::end);
		std::streamoff len = file.tellg();
		file.seekg(std::ios::beg);
		return (unsigned long)len;
	}
//father:Material Block
//child	: sub color chunk
void ParseSpecularColor()
{
	uint64_t filePos = 0;
	do
	{
		ReadAndParseColorChunk(static_materialList.back().baseMaterial.mBaseSpecularColor);
		filePos = fileIn.tellg();
	} while (filePos<static_currentChunkFileEndPos);
}
Example #5
0
static void copyKeyword( std::ifstream& is , std::ofstream& os) {
  std::ios::pos_type start_pos = is.tellg();
  skipKeyword( is );
  {
    std::ios::pos_type end_pos = is.tellg();
    long length = end_pos - start_pos;
    
    {
      char * buffer = new char[length];
      {
        is.seekg( start_pos );
        is.read( buffer , length );
      }
      os.write( buffer , length );
      delete[] buffer;
    }
  }
}
Example #6
0
/**
 * @brief read correlator meta-data and map to file positions
 * @description Nissa text correlator files contain meta-data in the form
 *              of comment lines. One line gives information about the
 *              contracted propagators in the form
 *
 *                S0_th0_m0_r0_ll ^ \dag S0_th0_m0_r0_ll
 *
 *              where we are (currently) interested in the indices
 *              on the m and r tokens. Another comment line specifies
 *              the spin content of the correlator in the form
 *              "P5P5" or "V1A0", for example. This function
 *              reads through the whole file and extracts the two
 *              m and two r indices as well as the spin combination.
 *              It constructs a key based on this information and stores
 *              the file position of the character after the newline behind
 *              the spin combination tag. Thus it stores the position of the
 *              beginning of the correlator corresponding to the constructed key.
 *
 * @param ifs file to be parsed
 * @param filemap output, map of file positions for the various correlators in the file
 */
inline void map_file(std::ifstream &ifs, std::map<std::string, std::iostream::pos_type> & filemap){
  if( !ifs.good() ){
    stop("map_file: input file stream not in a good state!");
  }

  std::string linebuf;
  std::string::size_type comment_pos;

  // currently the key for a two-point function consists of four unsigned integers (two mass and two r indices)
  // and the name of the spin combination stored in the correlator
  // a generalisation of the reader will have to modify this as well as the key construction
  // for now we store the numeric key components in this array
  unsigned int key_components[4];

  while( ifs.good() ){
    std::getline(ifs, linebuf);
    // we search for commented lines
    comment_pos = linebuf.find("#");
    if( comment_pos != std::string::npos ){
      // in these commented lines, we extract either
      // the current set of mass / r parameter combinations
      // or the current spin combination
      // the line looks like so:
      // " # Contraction of S0_th0_m0_r0_ll ^ \dag and S0_th0_m0_r0_ll"
      std::string::size_type contr_pos = linebuf.find("Contraction");
      if( contr_pos != std::string::npos ){
        std::vector<char> lbcopy( linebuf.size() + 1 );
        lbcopy[ linebuf.size() ] = '\0';
        memcpy( lbcopy.data(), linebuf.c_str(), linebuf.size() );
        unsigned int key_components_counter = 0;
        char * token = strtok(lbcopy.data(), "_");
        while( key_components_counter != 4 | token != NULL ){
          if( token[0] == 'm' || token[0] == 'r'){
            key_components[key_components_counter] = atoi(token+1);
            key_components_counter++;
          }
          token = strtok(NULL, "_");
        }
        if(key_components_counter != 4 && token == NULL){
          char message[200];
          snprintf(message, 200, "map_file: unable to construct key components in parsing of '%s'", linebuf.c_str());
          stop(message);
        }
      } else {
        // the line looks like so:
        // " # P5S0"
        std::string::size_type last_space_pos = linebuf.find_last_of(" ");
        std::string spin_comb = linebuf.substr(last_space_pos+1);
        // now we can build the key
        std::string key = make_key_2pt(key_components[0], key_components[2], key_components[1], key_components[3], spin_comb);
        // and store the position after the current newline as the starting point
        // of the present correlator
        filemap[ key ] = ifs.tellg();
      }
    }
  }
}
bool WLMatLib::MATReader::readMatrixDouble( Eigen::MatrixXd* const matrix, const ElementInfo_t& element, std::ifstream& ifs,
                const FileInfo_t& info )
{
    // Check some errors //
    // ----------------- //
    if( matrix == NULL )
    {
        wlog::error( LIBNAME ) << "Matrix object is null!";
        return false;
    }

    if( info.fileSize <= static_cast< size_t >( element.posData ) )
    {
        wlog::error( LIBNAME ) << "Data position is beyond file end!";
        return false;
    }

    if( element.dataType != DataTypes::miMATRIX )
    {
        wlog::error( LIBNAME ) << "Data type is not a matrix: " << element.dataType;
        return false;
    }

    const mArrayType_t arrayType = ArrayFlags::getArrayType( element.arrayFlags );
    if( arrayType != ArrayTypes::mxDOUBLE_CLASS )
    {
        wlog::error( LIBNAME ) << "Numeric Types does not match!";
        return false;
    }

    const std::streampos pos = ifs.tellg();

    // Read data //
    // --------- //
    ifs.seekg( element.posData );
    mDataType_t type;
    mNumBytes_t bytes;
    if( !readTagField( &type, &bytes, ifs ) )
    {
        wlog::error( LIBNAME ) << "Could not read Data Element!";
        ifs.seekg( pos );
        return false;
    }
    if( type != DataTypes::miDOUBLE )
    {
        wlog::error( LIBNAME ) << "Numeric Types does not match or compressed data, which is not supported: " << type;
        ifs.seekg( pos );
        return false;
    }

    matrix->resize( element.rows, element.cols );
    ifs.read( ( char* )matrix->data(), bytes );

    nextElement( ifs, element.posData, bytes );
    return true;
}
Example #8
0
	unsigned long Shader::getFileLength(std::ifstream& in)
	{
		if (!in.good()) return 0;

		in.seekg(0, in.end);
		unsigned long length = in.tellg();
		in.seekg(0, in.beg);

		return length;
	}
Example #9
0
    /**
     * initialize the laserxa files
     */
    void
    init ()
    {
      // read the info header
      this->close ();
      file_in_.open (filename_, std::ios::in | std::ios::binary);
      file_in_.seekg (0, std::ios::beg);
      file_in_.read ((char*) &info_, sizeof(LaserxaInfo));

      // length of size
      auto current_pos = file_in_.tellg ();
      file_in_.seekg (0, std::ios::end);
      auto end = file_in_.tellg ();

      data_count_ = (static_cast<size_t> (end)
	  - static_cast<size_t> (current_pos)
	      / static_cast<size_t> (sizeof(LaserxaData)));

    }
Example #10
0
int GetCommand::getFileSize(std::ifstream &ifs)
{

       	//http://washieagle.blogspot.jp/2010/01/stdfstream.html
	int eofPos;
	int begPos;
	
	//末尾
	ifs.seekg(0, std::ifstream::end);
	eofPos = ifs.tellg();
		
	ifs.clear();
	
	//先頭
	ifs.seekg(0, std::ifstream::beg);
	begPos = ifs.tellg();

	return eofPos - begPos;
}
		bool open(const char* path) {
			std::streampos tmp,tmp2;
			close();
			m_fp.close();
			m_fp.open(path,std::ios::binary);

			if (!m_fp.is_open())
				return false;

			m_fp.seekg(0,std::ios::beg);
			tmp = m_fp.tellg();
			m_fp.seekg(0,std::ios::end);
			tmp2 = m_fp.tellg();
			m_fp_size = (uint64_t)(tmp2 - tmp);
			m_fp.seekg(0,std::ios::beg);
			m_fp_offs = 0U;

			return true;
		}
Example #12
0
unsigned long jE::getFileLength(std::ifstream& file)
{
    if(!file.good()) return 0;

    //unsigned long pos=file.tellg();
    file.seekg(0, std::ios::end);
    unsigned long len = file.tellg();
    file.seekg(std::ios::beg);

    return len;
}
Example #13
0
Csv_input_pointset_dialog::Csv_input_pointset_dialog( std::ifstream& infile,
        QWidget* parent ,
        const char* name )
    : QWidget( parent) {

    setupUi(this);

    std::streampos mark = infile.tellg();
    std::string str;
    std::getline(infile, str);
    QString qstr(str.c_str());

//  QTextStream inFileStream(infile,QIODevice::ReadWrite);
//  QString str;
//  inFileStream >> str;
//  inFileStream.readLine();
    QStringList property_names = qstr.split(",");


    X_col_name_->addItems(property_names);
    X_col_name_->addItem("None");
    Y_col_name_->addItems(property_names);
    Y_col_name_->addItem("None");
    Z_col_name_->addItems(property_names);
    Z_col_name_->addItem("None");


    //Set default selection
    X_col_name_->setCurrentIndex(0);
    Y_col_name_->setCurrentIndex(std::min(1,property_names.size()));
    Z_col_name_->setCurrentIndex(std::min(2,property_names.size()));
    // make a preview of the file

    QString text;
    std::string line;

    int count = 0;
    const int limit = 50;

    // Read up to "limit" lines
    while( std::getline( infile, line ) && count < limit ) {
        line += "\n";
        text.append( line.c_str() );
        count ++;
    }

    text_preview_->setPlainText( text );

    // set the stream back to where it was
    infile.clear();
    infile.seekg( mark );

    name_->setFocus();
}
Example #14
0
File: pe.cpp Project: haofree/rp
CPU::E_CPU PE::extract_information_from_binary(std::ifstream &file)
{
    RP_IMAGE_DOS_HEADER imgDosHeader = {0};
    RP_IMAGE_NT_HEADERS32 imgNtHeaders32 = {0};
    CPU::E_CPU cpu = CPU::CPU_UNKNOWN;

    std::cout << "Loading PE information.." << std::endl;

    /* Remember where the caller was in the file */
    std::streampos off = file.tellg();

    file.seekg(0, std::ios::beg);
    file.read((char*)&imgDosHeader, sizeof(RP_IMAGE_DOS_HEADER));

    file.seekg(imgDosHeader.e_lfanew, std::ios::beg);
    /* 
     * Yeah, in fact, we don't know yet if it is a x86/x64 PE ; 
     * so just we grab the signature field, FILE_HEADER and the field Magic 
     */
    file.read((char*)&imgNtHeaders32, sizeof(unsigned int) + sizeof(RP_IMAGE_FILE_HEADER) + sizeof(unsigned int));
    
    if(imgNtHeaders32.Signature != RP_IMAGE_NT_SIGNATURE)
        RAISE_EXCEPTION("This file doesn't seem to be a correct PE (bad IMAGE_NT_SIGNATURE)");

    switch(imgNtHeaders32.OptionalHeader.Magic)
    {
        case RP_IMAGE_NT_OPTIONAL_HDR32_MAGIC:
        {
            cpu = CPU::CPU_x86;
            /* Ok, now we can allocate the good version of the PE Layout */
            /* The 32bits version there! */
            init_properly_PELayout<x86Version>();
            break;
        }

        case RP_IMAGE_NT_OPTIONAL_HDR64_MAGIC:
        {
            cpu = CPU::CPU_x64;
            init_properly_PELayout<x64Version>();
            break;
        }

        default:
            RAISE_EXCEPTION("Cannot determine the CPU type");
    }
    
    /* Now we can fill the structure */
    std::memcpy(&m_pPELayout->imgDosHeader, &imgDosHeader, m_pPELayout->get_image_dos_header_size());

    m_pPELayout->fill_nt_structures(file);

    file.seekg(off);
    return cpu;
}
Example #15
0
 bool open(const char_type* file_name)
 {
     in.open(file_name,std::ios::binary);
     if(in)
     {
         in.seekg(0,std::ios::end);
         size_ = in.tellg();
         in.seekg(0,std::ios::beg);
     }
     return in.good();
 }
//father:Material Block
//child	: Mapping File Path  (Map option) 
void ParseSpecularMap()
{
	//data:sub chunks
	uint64_t filePos = 0;
	do
	{
		//mapName-mapFilePath pair will be added in this function
		ReadAndParseMapChunk(static_materialList.back().specularMapName);
		filePos = fileIn.tellg();
	} while (filePos<static_currentChunkFileEndPos);
}
//*************************************************
//father:Material Block
//child	: sub color chunk
void ParseAmbientColor()
{
	//data:sub chunks

	uint64_t filePos = 0;
	do
	{
		ReadAndParseColorChunk(static_materialList.back().baseMaterial.mBaseAmbientColor);
		filePos = fileIn.tellg();
	} while (filePos<static_currentChunkFileEndPos);
}
Example #18
0
void initAstFromString(std::ifstream & in_file) {
  SgScopeStatement * scope = SageBuilder::buildBasicBlock();

  AstFromString::c_sgnode = scope;
  SageBuilder::pushScopeStack(scope);

  SgName pow_name("pow");
  SgFunctionDeclaration * pow_decl = SageBuilder::buildNondefiningFunctionDeclaration(
                                       pow_name,
                                       SageBuilder::buildDoubleType(),
                                       SageBuilder::buildFunctionParameterList(
                                         SageBuilder::buildInitializedName("base", SageBuilder::buildDoubleType()),
                                         SageBuilder::buildInitializedName("exp", SageBuilder::buildDoubleType())
                                       ),
                                       scope,
                                       NULL
                                     );
  scope->insert_symbol(pow_name, new SgFunctionSymbol(pow_decl));

  SgName sqrt_name("sqrt");
  SgFunctionDeclaration * sqrt_decl = SageBuilder::buildNondefiningFunctionDeclaration(
                                       sqrt_name,
                                       SageBuilder::buildDoubleType(),
                                       SageBuilder::buildFunctionParameterList(
                                         SageBuilder::buildInitializedName("v", SageBuilder::buildDoubleType())
                                       ),
                                       scope,
                                       NULL
                                     );
  scope->insert_symbol(sqrt_name, new SgFunctionSymbol(sqrt_decl));

  SgName abs_name("fabs");
  SgFunctionDeclaration * abs_decl = SageBuilder::buildNondefiningFunctionDeclaration(
                                       abs_name,
                                       SageBuilder::buildDoubleType(),
                                       SageBuilder::buildFunctionParameterList(
                                         SageBuilder::buildInitializedName("v", SageBuilder::buildDoubleType())
                                       ),
                                       scope,
                                       NULL
                                     );
  scope->insert_symbol(abs_name, new SgFunctionSymbol(abs_decl));

  in_file.seekg (0, in_file.end);
  int length = in_file.tellg();
  in_file.seekg (0, in_file.beg);

  char * tmp_char_str = new char [length + 1];
  in_file.read(tmp_char_str, length);
  tmp_char_str[length] = 0;

  AstFromString::c_char = tmp_char_str;
  AstFromString::afs_skip_whitespace();
}
Example #19
0
	size_t getFileSize(std::ifstream& file)
	{
		if(!file.good()) return 0;
	    
		//size_t pos = file.tellg();
		file.seekg(0,std::ios::end);
		std::streamoff len = file.tellg();
		file.seekg(std::ios::beg);
	    
		return (size_t)len;
	}
Example #20
0
/******************** SUPPORT FUNCTIONS *********************/
size_t nextReadPosition(std::ifstream& ifs, size_t off = 0) {
  ifs.seekg(off);
  size_t candidate = off;
  char line[MAX_BUFFER_SIZE];
  line[0] = 0;
  // look for the first occurance of '@' at the beginning of a line
  while(line[0] != '@' && !ifs.eof()) {
    candidate = ifs.tellg();
    ifs.getline(line, MAX_BUFFER_SIZE);
  }
  // end of file reached and no reads have been found
  if (ifs.eof()) {
    return off;
  }
  size_t tmp = ifs.tellg();  
  // read the next line to double check that '@' defines a proper start of a read
  ifs.getline(line, MAX_BUFFER_SIZE);
  candidate = (line[0] != '@') ? candidate : tmp;
  return candidate;
}
Example #21
0
bool FRAME::read(std::ifstream & s, PIXELTYPE pixelFormat) {
    bool result = s & size
        && s & magicNumber
        && s & chunks_old
        && s & duration
        && s & reserved
        && s & chunkCount;

    if (result) {
        //std::cout << std::hex << "DEBUG Frame: magicNumber: " << magicNumber << " chunks_old: " << chunks_old << std::dec << "\n";
        chunks.reserve(chunkCount);
        for (size_t c = 0; c < chunkCount && result; c++) {
            DWORD size;
            WORD type;
            constexpr size_t CHUNK_HEADER_SIZE = sizeof(size) + sizeof(type);
            auto p = s.tellg();
            result = result && s & size && s & type;
            //auto p2 = s.tellg();
            //std::cout << std::hex << "0x" << p2 << ":DEBUG Chunk: size: " << size << " type: " << type << std::dec << "\n";
            switch (type) {
            case PALETTE_OLD_0x0004: {
                case PALETTE_OLD_0x0011:
                chunks.emplace_back(PALETTE_OLD_CHUNK(s), type);
                break;
            }
            case LAYER_0x2004: {
                chunks.emplace_back(LAYER_CHUNK(s), type);
                break;
            }
            case CEL_0x2005: {
                chunks.emplace_back(CEL_CHUNK(s, pixelFormat, size - CHUNK_HEADER_SIZE), type);
                break;
            }
            case FRAME_TAGS_0x2018: {
                chunks.emplace_back(TAG_CHUNK(s), type);
                break;
            }
            case PALETTE_0x2019: {
                chunks.emplace_back(PALETTE_CHUNK(s), type);
                break;
            }
            case SLICE_0x2022: {
                chunks.emplace_back(SLICE_CHUNK(s), type);
                break;
            }
            default:
                //std::cout << "^ not parsed\n";
                s.seekg(size + p); // skip data
            }
            result = result && s.good();
        }
    }
    return result;
}
unsigned long getFileLength(std::ifstream& file)
{
    if (!file.good())
    {
        return 0;
    }

    file.seekg(0, std::ios::end);
    unsigned long length = file.tellg();
    file.seekg(std::ios::beg);
    
    return length;
}
Example #23
0
    uint16_t _read_16(uint32_t offset) {
        uint16_t value;
        uint32_t tell;

        tell = _in.tellg();

        _in.seekg(_offset + offset, std::ios::beg);
        _in.read((char*)&value, 2);

        _in.seekg(tell, std::ios::beg);

        return BIG2LE_16(value);
    }
Example #24
0
Utils::Utils(int size, std::ifstream &f)
		: clearFirst(false), data(""), size(0), row(0), col(0) {
	std::streampos cPos = f.tellg();
	std::string theline;
	this->size = size;
	getline(f, theline);
	for (int i = 0; i < size; i++) {
		getline( f, theline );
		data += theline.substr(0,size);
	}
	// reset the file stream
	f.seekg(cPos);
}
Example #25
0
void DTMImage::ReadBinaryHeader( std::ifstream & ifs )
{
  ifs.seekg(0,std::ios::beg);

  int Dimensions[3];
  for ( int i = 0; i < 3; ++i ) ifs.read(reinterpret_cast<char *>(&Dimensions[i]), sizeof(int));
  this->SetDimensions(Dimensions);
  for ( int i = 0; i < 3; ++i ) ifs.read(reinterpret_cast<char *>(&this->ImageData::origin[i]), sizeof(double));
  for ( int i = 0; i < 3; ++i ) ifs.read(reinterpret_cast<char *>(&this->ImageData::spacing[i]), sizeof(double));
  for ( int i = 0; i < 3; ++i ) ifs.read(reinterpret_cast<char *>(&this->ImageData::indexIncrement[i]), sizeof(int));
  ifs.read(reinterpret_cast<char *>(&this->scalarType), sizeof(int));

  this->startOfScalars = ifs.tellg();
}
Example #26
0
int utr_io_count_string_in_file(
								std::ifstream & File,
								const string & To_find
)
{
  int starting_point = File.tellg();
  int count = std::count(std::istream_iterator<string>(File),
					   std::istream_iterator<string>(),
						 To_find);
  File.clear();
  File.seekg(starting_point);
  assert(File.good());
  return count;
}
Example #27
0
        inline uint32_t lookup3(std::ifstream &stream, uint32_t length, const uint32_t &init)
        {
            auto hash = init;
            std::vector<char> buffer(length);

            auto pos = stream.tellg();

            stream.read(buffer.data(), length);
            hash = hashlittle(buffer.data(), length, hash);

            stream.seekg(pos);

            return hash;
        }
Example #28
0
bool Field::Load(std::ifstream& f, int shift){
	S_LOG("Load");
	auto current = std::ios_base::cur;
	if (f.good()){
		f.seekg(shift, current);
                log(logxx::debug) << "Current position: 0x" << std::hex << f.tellg() << std::dec << logxx::endl;
                uint32_t fieldLength(0);
                char optionalField[2];
                f.read(optionalField, 2);
                check_error(optionalField);
                if (
                        std::strncmp(optionalField, "PN", 2) == 0 ||
                        std::strncmp(optionalField, "LO", 2) == 0 ||
                        std::strncmp(optionalField, "DA", 2) == 0
                        ){
                        uint16_t shortFieldLength(0);
                        fread(shortFieldLength);
                        fieldLength = shortFieldLength;
                } else{
                        f.seekg(-2, std::ios_base::cur);
                        fread(fieldLength);
                }
                
                static const decltype(fieldLength) maxLength = 100;
                
                if (fieldLength == 0){
                        log(logxx::warning) << "Field length is zero, nothing to read!" << logxx::endl;
                        return false;
                } else if (fieldLength > maxLength){
                        log(logxx::warning) << "Too large field: " << fieldLength <<
                                "; maximum allowed is: " << maxLength << logxx::endl;
                        return false;
                }
		std::unique_ptr<char[]> cValue(new char[fieldLength]);
		f.read(cValue.get(), fieldLength);
		check_error(cValue);
		try {
			value.assign(cValue.get(), fieldLength);
			ProcessValue();
			return true;
		} catch (const std::exception& e){
			log(logxx::warning) << "Cought an exception: " << e.what() << logxx::endl;
			value.assign('%', fieldLength);
			return true;
		}
	} else {
		log(logxx::error) << "Can't read file" << logxx::endl;
		return false;
	}
}
Example #29
0
void AudioStreamingServer::StreamFile(const std::shared_ptr<ISocket>& clientSocket, std::ifstream& file, HttpContentType contentType) const {
    file.seekg(0, file.end);
    int fileLength = file.tellg();
    HttpResponse response(HTTP_1_1, OK, contentType, fileLength);
    SendResponseHeader(clientSocket, response);
    
    file.seekg(0, file.beg);
    char sendbuf[DEFAULT_BUFFER_SIZE] = { 0 };
    file.read(sendbuf, DEFAULT_BUFFER_SIZE);
    while(file.gcount() > 0) {
        clientSocket->Send(sendbuf, file.gcount());
        file.read(sendbuf, DEFAULT_BUFFER_SIZE);
    }
}
Example #30
0
bool rspfFgdcTxtDoc::findKey(
    std::ifstream& str, bool seekBack, const std::string& key, std::string& value)
{
    bool result = false;

    std::vector<rspfString> fgdcKeyValue;
    rspfString separator = ":";
    rspfString line;
    rspfKeywordlist projectionKwl;
    std::streampos currentPosition = str.tellg();

    while ( !str.eof() )
    {
        // Read line:
        std::getline( str, line.string() );

        if ( line.size() )
        {
            // Eat white space.
            line.trim();

            // Split between ':'
            fgdcKeyValue.clear();
            line.split(fgdcKeyValue, separator, false);
            if ( fgdcKeyValue.size() == 2 )
            {
                fgdcKeyValue[0].trim();

                if ( fgdcKeyValue[0].size() )
                {
                    if ( fgdcKeyValue[0] == key )
                    {
                        // Found it.  Initialize value and get out.
                        result = true;
                        fgdcKeyValue[1].trim();
                        value = fgdcKeyValue[1].string();
                        break; // from while loop.
                    }
                }
            }
        }
    }

    if ( seekBack )
    {
        str.seekg(currentPosition);
    }

    return result;
}