예제 #1
0
int TextFileScript::ReadTextFile (istream& in, void* addr1, void* addr2, void* addr3, void* addr4) {
    int line_height;
    char delim;
    char pathname[BUFSIZ];

    TextFileComp* textfilecomp = (TextFileComp*)addr1;

    in >> line_height;
    ParamList::skip_space(in); 
    in >> delim; 
    if (delim == ',' && in.good()) {
	ParamList::skip_space(in);
	if (ParamList::parse_pathname(in, pathname, BUFSIZ, textfilecomp->GetBaseDir()) != 0) 
	    return -1;
    }

    if (!in.good()) {
	return -1;
    }
    else {
	textfilecomp->_pathname = strdup(pathname);
    	TextGraphic* tg = new TextGraphic("", line_height); 	
	tg->SetFont(psstdfont);
	tg->SetColors(psblack, nil);
	tg->FillBg(false);
	textfilecomp->SetGraphic(tg);
        return 0;
    }
}
예제 #2
0
shared_ptr<DocumentDatabase> DocumentDatabaseBuilder::create(istream& keywordsStream,
		istream& documentsStream) {
	shared_ptr<DocumentDatabase> dbPtr = make_shared<DocumentDatabase>();

	if (!keywordsStream.good()) {
		cerr << "Bad keywords stream." << endl;
		return nullptr;
	}

	shared_ptr<Document> keywords = documentBuilderPtr->createOne(keywordsStream);
	unordered_set<string> uniqueKeywords(
		keywords->getStemmedContent().begin(),
		keywords->getStemmedContent().end());

	keywords->getStemmedContent() = vector<string>(
		uniqueKeywords.begin(), uniqueKeywords.end());
	
	dbPtr->getKeywords() = keywords;

	if (!documentsStream.good()) {
		cerr << "Bad documents stream." << endl;
		return nullptr;
	}

	dbPtr->getDocuments() = documentBuilderPtr->createMany(documentsStream);

	return dbPtr;
}
예제 #3
0
bool
fcnn::internal::read_comment(istream &is, string &s)
{
    if (!is.good() || is.eof()) return false;
    char c;
    s.clear();
    c = is.peek();
    if (c != '#') return false;
    is.get(c);

start_line:
    do { is.get(c); }
    while ((is.good() && !is.eof()) && ((c == ' ') || (c == '\t')));
    if (is.eof()) return true;
    if (is.fail()) return false;
    while ((is) && (c != '\n')) {
        s += c;
        is.get(c);
    }
    if (is.eof()) return true;
    if (is.fail()) return false;
    if (c == '\n') {
        if (is.peek() == '#') { s += c; goto start_line; }
        else return true;
    }
    return true;
}
예제 #4
0
	void read(istream& is)
	{
		vector<char> line;
		while (is.good())
		{
			// Read until the end of the line is found.
			line.clear();
			int c;
			while (is.good() && (c = is.get()) != '\n')
				line.push_back((char)c);

			// Skip empty lines or comment lines.
			if (line.empty() || line[0] == '#')
				continue;

			// Parse the line, moving its contents into one of the sets.
			size_t sol = 1;
			for (sol = 1; sol < line.size() && (line[sol] == ' ' || line[sol] == '\t'); sol++);
			string param(&line[sol], line.size()-sol);

			switch (line[0]) {
				case '+': additions.insert(param); break;
				case '-': deletions.insert(param); break;
				case 'p': patches.insert(param); break;
				default: std::cerr << "ignoring garbage line " << string(&line[0], line.size()) << " in index\n";
			}
		}
	}
예제 #5
0
파일: GEO.cpp 프로젝트: wdas/partio
string scanString(istream& input)
{
    // TODO: this code does not check for buf overrun
    // TODO: this code doesn't properly check for FEOF condition
    char buf[4096];
    char *ptr=buf;
    char c;
    while(input.good()){
        input.get(c);
        if(!isspace(c)) break;
    }
    if(!input.good()) return "";

    if(c!='"'){
        while(input.good()){
            *ptr++=c;
            input.get(c);
            if(isspace(c)) break;
        }
    }else{
        while(input.good()){
            input.get(c);
            if(c=='\\'){
                input.get(c);
                *ptr++=c;
            }else if(c=='"'){
                break;
            }else{
                *ptr++=c;
            }
        }
    }
    *ptr++=0;
    return string(buf);
}
예제 #6
0
파일: pivot.cpp 프로젝트: 0day1day/bap
/**
   Parses an input stream.  The file has format: <gadget type> <reg> <offset>.
*/
pivot_set PIVOT_parseinput(istream &f) {
  pivot_set ps; 

  while (f.good()) {
    pivot_t p;
    string s;


    /* Read gadget address. */
    f >> hex >> p.address;

    if (!f.good()) break;

    /* Set pivot type. */
    f >> s;
    p.t = PIVOT_parse_pivottype(s);
    if (p.t == UNKNOWN) {
      break;
    }

    /* Read register name. */
    f >> s;
    p.base = PIVOT_string_reg(s);
    
    /* Read offset. */
    f >> hex >> p.offset;

    /* Add pivot to pivot set. */
    ps.insert(p);
  }

  return ps; /* return by value; slow but easy */
}
예제 #7
0
파일: Graph.cpp 프로젝트: tts-ll/grafalgo
/** Read adjacency list from an input stream, add it to the graph.
 *  @param in is an open input stream
 *  @return true on success, false on error.
 */
bool Graph::readAdjList(istream& in) {
	if (!Util::verify(in,'[')) return false;
	vertex u;
	if (!Adt::readIndex(in,u)) return false;
	if (u > n()) expand(u,M());
	if (!Util::verify(in,':')) return false;
	while (in.good() && !Util::verify(in,']')) {
		vertex v; edge e;
		if (!Adt::readIndex(in,v)) return false;
		if (v > n()) expand(v,M());
		if (m() >= M()) expand(n(),max(1,2*M()));
		if (!Util::verify(in,'#')) {
			if (u < v) join(u,v);
		} else {
			if (!Util::readInt(in,e)) return false;
			if (e >= M()) expand(n(),e);
			if (u < v) {
				if (joinWith(u,v,e) != e) return false;
			} else {
				if ((u == left(e)  && v != right(e)) ||
				    (u == right(e) && v != left(e)))
					return false;
			}
		}
	}
	return in.good();
}
//---------------------------------------------------------------------------
unique_ptr<Expression> ExpressionParser::parseSingleExpression(istream& input, ExpressionType lastExpression, Environment& environment)
{
   // read
   harriet::skipWhiteSpace(input);
   char a = input.get();
   if(!input.good())
      return nullptr;

   // other single letter operators
   if(a == '(') return make_unique<OpeningPharentesis>();
   if(a == ')') return make_unique<ClosingPharentesis>();
   if(a == '+') return make_unique<PlusOperator>();
   if(a == '-') { if(lastExpression==ExpressionType::TBinaryOperator || lastExpression==ExpressionType::TUnaryOperator || lastExpression==ExpressionType::TOpeningPharentesis) return make_unique<UnaryMinusOperator>(); else return make_unique<MinusOperator>(); }
   if(a == '*') return make_unique<MultiplicationOperator>();
   if(a == '/') return make_unique<DivisionOperator>();
   if(a == '%') return make_unique<ModuloOperator>();
   if(a == '^') return make_unique<ExponentiationOperator>();
   if(a == '&') return make_unique<AndOperator>();
   if(a == '|') return make_unique<OrOperator>();
   if(a=='>' && input.peek()!='=') return make_unique<GreaterOperator>();
   if(a=='<' && input.peek()!='=') return make_unique<LessOperator>();
   if(a=='!' && input.peek()!='=') return make_unique<NotOperator>();
   if(a=='=' && input.peek()!='=') return make_unique<AssignmentOperator>();

   // check for string
   char b = input.get();
   if(a=='"') {
      string result;
      while(b!='"' && a!='\\') {
         if(!input.good())
            throw harriet::Exception{"unterminated string expression"};
         result.push_back(b);
         a = b;
         b = input.get();
      }
      return make_unique<StringValue>(result);
   }

   // check for two signed letters
   if(input.good()) {
      if(a=='=' && b=='=') return make_unique<EqualOperator>();
      if(a=='>' && b=='=') return make_unique<GreaterEqualOperator>();
      if(a=='<' && b=='=') return make_unique<LessEqualOperator>();
      if(a=='!' && b=='=') return make_unique<NotEqualOperator>();
      input.unget();
   } else {
      input.clear();
   }

   // check for a number
   input.unget();
   if(isdigit(a)) {
      int32_t intNum;
      input >> intNum;
      if(input.peek()=='.' && input.good()) {
         float floatNum;
         input >> floatNum;
         return make_unique<FloatValue>(floatNum+intNum);
      } else {
         return make_unique<IntegerValue>(intNum);
예제 #9
0
int ChessIO::scan_pgn(istream &game_file, vector<string> &contents)
{
    Board board;
    int c;

    while (game_file.good() && !game_file.eof())
    {
        // Collect the header:
        long first;
        vector<Header> hdrs;
        string eventStr;
        collect_headers(game_file, hdrs, first);
        if (get_header(hdrs,"Event",eventStr))
        {
           // We have the headers, munge them into a single-line game
           // description. Append the index to the game so the GUI
           // can navigate to the game when the user clicks on the
           // description.
           string descr;
           get_game_description(hdrs, descr, first);
           contents.push_back(descr);
        }
        hdrs.clear();

        while (game_file.good() && !game_file.eof())
        {
           if ((c = game_file.get()) == '[')
           {
               game_file.putback(c);
               break;
           }
        }
    }
    return 1;
}
예제 #10
0
파일: data_mult.cpp 프로젝트: yqxian/zsl
static void
loadmult_datafile_sub(istream &f, bool binary, const char *fname, 
                  xvec_t &xp, yvec_t &yp, int &maxdim, int maxrows)
{
  cout << "# Reading file " << fname << endl;
  if (! f.good())
    assertfail("Cannot open " << fname);

  int pcount = 0;
  while (f.good() && maxrows--)
    {
	double y;
      	SVector x;
	y = (f.get());
        x.load(f);
      
      if (f.good())
        {          
          xp.push_back(x);
          yp.push_back(y);
          pcount += 1;
          if (x.size() > maxdim)
            maxdim = x.size();
        }
    }
  cout << "# Read " << pcount << " examples." << endl;
  

}
예제 #11
0
/**
 * \brief Tokenize a stream of XML by chopping it up into XMLTokens and
 *        returning a vector of these tokens.
 *
 * This function consumes all data in the stream
 */
vector<XMLToken>
XMLToken::tokenize(istream& istrm) {
  vector<XMLToken> tokens;
  while (istrm.good()) {
    chomp(istrm);
    if (!istrm.good()) break;

    // parse tag
    if (istrm.peek() == '<') {
      string tagname;
      bool isEndTag = false;

      istrm.get(); // skip <
      chomp(istrm);
      if (!istrm.good()) break;
      if (istrm.peek() == '/') {
          istrm.get(); // skip /
          isEndTag = true;
      }

      while (istrm.good() && (istrm.peek() != '>'))
          tagname += istrm.get();
      istrm.get(); // skip >
      tokens.push_back(XMLToken(tagname,isEndTag));
    } else {
      // parse string
      string buf = "";
      while (istrm.good() && (istrm.peek() != '<'))
          buf += istrm.get();
      tokens.push_back(XMLToken(buf));
    }
  }
  return tokens;
}
예제 #12
0
void tune::readX0(istream &is) 
{
   int c;
   while (is.good() && (c = is.get()) != '(') ;
   for (int i = 0; is.good() && i < tune::NUM_TUNING_PARAMS; i++) {
      is >> tune::tune_params[i].current;
   }
}
예제 #13
0
list<string> getImageList(istream& input) {
  list<string> imlist;
  while (!input.eof() && input.good()) {
    string imname;
    input >> imname;
    if(!input.eof() && input.good())
      imlist.push_back(imname);
  }
  return imlist;
}
예제 #14
0
파일: input.cpp 프로젝트: mkoeppe/Normaliz
// eats up a comment, stream must start with "/*", eats everything until "*/"
void skip_comment(istream& in) {
    int i = in.get();
    int j = in.get();
    if (i != '/' || j != '*') {
        throw BadInputException("Bad comment start!");
    }
    while (in.good()) {
        in.ignore(numeric_limits<streamsize>::max(), '*'); //ignore everything until next '*'
        i = in.get();
        if (in.good() && i == '/') return; // successfully skipped comment
    }
    throw BadInputException("Incomplete comment!");
}
예제 #15
0
파일: egs_rndm.cpp 프로젝트: tener32/EGSnrc
bool EGS_RandomGenerator::setState(istream &data) {
    if( !egsGetI64(data,count) ) return false;
    int np1;
    data >> np1 >> ip;
    if( !data.good() || data.fail() || data.eof() ) return false;
    if( np1 < 1 ) return false;
    if( np1 != np && np > 0 ) {
        delete [] rarray; rarray = new EGS_Float [np1];
    }
    np = np1;
    for(int j=0; j<np; j++) data >> rarray[j];
    if( !data.good() ) return false;
    return setPrivateState(data);
}
예제 #16
0
int 
readDataSentence(istream &f, strings_t &s, int &expected)
{
  strings_t line;
  s.clear();
  while (f.good())
    if (readDataLine(f, s, expected))
      break;
  while (f.good())
    if (! readDataLine(f, s, expected))
      break;
  if (expected)
    return s.size() / expected;
  return 0;
}
예제 #17
0
//read coefficients from a stream. This assumes pairs of bitstring and values, e.g.
//010100 1.232
//101011 65.432
int hypercube_lowd::read_func_labeled(istream &in)
{
	int i=0, count;
	char gt[dim+2];
	if (in.bad())
	{
		cerr <<"hypercube_lowd::read_func_labeled: bad stream\n";
		return HC_BADARG;
	}
	count=0;
	while(in.good() && count<(1<<dim))
	{
		i=0;
		in >>gt;
		for (int k=0; k<dim; k++)
			if (gt[k]=='1') i+=1<<k;
		in >>func[i];
		count++;
		in.ignore(100, '\n');
	}
	if (count<(1<<dim))
	{
		cerr <<"hypercube_lowd::read_func: file end reached after "<<i<<" values!\n";
		return HC_BADARG;
	}
	return 0;
}
예제 #18
0
int FixedFieldBuffer::ReadHeader(istream & stream){
    char *str = new char[headerStrSize+1];
    int numFields, *fieldSize;
    int result = FixedLengthBuffer::ReadHeader(stream);
    if(!result) return -1;

    //read header string.    
    stream.read(str, headerStrSize);
    if(!stream.good()) return -1;

    if(strncmp(str, headerStr, headerStrSize)!=0) return -1;

    stream.read((char*)&numFields, sizeof(numFields));
    if(!stream) return -1;

    for(int i=0; i<numFields; i++)
        stream.read((char*)&fieldSize[i], sizeof(fieldSize[i]));

    if(Initialized){
        if(numFields!=NumFields) return -1;
        for(int j=0; j<numFields; j++)
            if(fieldSize[j]!=FieldSize[j]) return -1;
        return stream.tellg();
    }
    Init(numFields, fieldSize);
    return stream.tellg();
}
예제 #19
0
int FixedFieldBuffer :: ReadHeader(istream & stream)
{
   char str[6];
   int numFields, *fieldSize;
   int result;

   result = FixedLengthBuffer::ReadHeader(stream);

   if (result < 0) return -1;
   stream.read(str,headerStrSize3);
   if (!stream.good()) return -1;
   if (strncmp (str,headerStr3,headerStrSize3)!=0) return -1;
   stream.read((char *)&numFields, sizeof(numFields));
   if (!stream) return -1;
   fieldSize = new int [numFields];
   for(int i =0; i < numFields;i++)
     stream.read((char *)&fieldSize[i], sizeof(fieldSize[i]));

/*   if (Initialized){
     if (numFields != NumFields) return -1;
     for(int j = 0; j < numFields; j++)
       if (fieldSize[j] != FieldSize[j] ) return -1;
     return stream.tellg();
   }
   Init(numFields,fieldSize);
   return stream.tellg();*/ return 1;
}
예제 #20
0
파일: Session.cpp 프로젝트: apex-hughin/LyX
void LastFilePosSection::read(istream & is)
{
	string tmp;
	do {
		char c = is.peek();
		if (c == '[')
			break;
		getline(is, tmp);
		if (tmp == "" || tmp[0] == '#' || tmp[0] == ' ')
			continue;

		try {
			// read lastfilepos
			// pos, file\n
			FilePos filepos;
			string fname;
			istringstream itmp(tmp);
			itmp >> filepos.pit;
			itmp.ignore(2);  // ignore ", "
			itmp >> filepos.pos;
			itmp.ignore(2);  // ignore ", "
			getline(itmp, fname);
			if (!FileName::isAbsolute(fname))
				continue;
			FileName const file(fname);
			if (file.exists() && !file.isDirectory()
			    && lastfilepos.size() < num_lastfilepos)
				lastfilepos[file] = filepos;
			else
				LYXERR(Debug::INIT, "LyX: Warning: Ignore pos of last file: " << fname);
		} catch (...) {
			LYXERR(Debug::INIT, "LyX: Warning: unknown pos of last file: " << tmp);
		}
	} while (is.good());
}
예제 #21
0
파일: Session.cpp 프로젝트: apex-hughin/LyX
void LastOpenedSection::read(istream & is)
{
	string tmp;
	do {
		char c = is.peek();
		if (c == '[')
			break;
		getline(is, tmp);
		if (tmp.empty() || tmp[0] == '#' || tmp[0] == ' ')
			continue;

		try {
			LastOpenedFile lof;
			istringstream itmp(tmp);
			itmp >> lof.active;
			itmp.ignore(2);  // ignore ", "
			string fname;
			getline(itmp, fname);
			if (!FileName::isAbsolute(fname))
				continue;

			FileName const file(fname);
			if (file.exists() && !file.isDirectory()) {
				lof.file_name = file;
				lastopened.push_back(lof);
			} else {
				LYXERR(Debug::INIT, 
					"LyX: Warning: Ignore last opened file: " << tmp);
			}
		} catch (...) {
			LYXERR(Debug::INIT,
				"LyX: Warning: unknown state of last opened file: " << tmp);
		}
	} while (is.good());
}
예제 #22
0
int
readDataLine(istream &f, strings_t &line, int &expected)
{
  int obtained = 0;
  while (f.good())
    {
      int c = skipBlank(f);
      if (c == '\n' || c == '\r')
        break;
      string s;
      f >> s;
      if (! s.empty())
        {
          line.push_back(s);
          obtained += 1;
        }
    }
  int c = f.get();
  if (c == '\r' && f.get() != '\n')
    f.unget();
  if (obtained > 0)
    {
      if (expected <= 0)
        expected = obtained;
      else if (expected > 0 && expected != obtained)
        {
          cerr << "ERROR: expecting " << expected 
               << " columns in data file." << endl;
          exit(10);
        }
    }
  else
    skipSpace(f);
  return obtained;
}
예제 #23
0
파일: csv_parser.cpp 프로젝트: alyst/zorba
inline bool peek( istream &is, char &c ) {
  char const temp = is.peek();
  bool const peeked = is.good();
  if ( peeked )
    c = temp;
  return peeked;
}
예제 #24
0
void CL_TimeOfDay::FromStream (istream& s)
{
    CL_String rep;
    char c;
    long count = 0;
    char fill_char = s.fill ();
    
    while (s.get (c) && c == fill_char);
    if (!s.good() || s.eof()) {
        _numSecs = 0;
        return;
    }
    do {
        if (isalnum (c) || c == ':') {
            rep.Append (c);
            count++;
        }
        else
            break;
    } while (s.get (c));

    long n = ParseAndConvert (rep);
    if (n > 0) {
        if (!s.eof())
            s.putback (c);
        _numSecs = n;
    }
    else {
        s.seekg (s.tellg() - count, istream::cur);
        _numSecs = 0;
    }
}
예제 #25
0
void binary2source(ostream &os,istream &is)
{
	os.setf(ios::hex,ios::basefield);

	os << '{' << endl;
	
	bool begin = true;
	while (is.good() && !is.eof())
	{
		unsigned char buffer[16];
		is.read((char *) buffer,16);
		
		int size = is.gcount();
		if (size>0 && !begin)
		{
			os << ',';
			os << endl;
		}

		begin = false;

		for (int i=0; i<size;i++)
		{
			os << "0x" << setw(2) << setfill('0') << (unsigned int)buffer[i];
			if (i<size-1)
				os << ',';
		}

	}

	os << endl << "};" << endl;
}
예제 #26
0
파일: plogg.cpp 프로젝트: JamesLinus/plogg
bool OggDecoder::read_page(istream& stream, ogg_sync_state* state, ogg_page* page) {
  int ret = 0;

  // If we've hit end of file we still need to continue processing
  // any remaining pages that we've got buffered.
  if (!stream.good())
    return ogg_sync_pageout(state, page) == 1;

  while((ret = ogg_sync_pageout(state, page)) != 1) {
    // Returns a buffer that can be written too
    // with the given size. This buffer is stored
    // in the ogg synchronisation structure.
    char* buffer = ogg_sync_buffer(state, 4096);
    assert(buffer);

    // Read from the file into the buffer
    stream.read(buffer, 4096);
    int bytes = stream.gcount();
    if (bytes == 0) {
      // End of file. 
      continue;
    }

    // Update the synchronisation layer with the number
    // of bytes written to the buffer
    ret = ogg_sync_wrote(state, bytes);
    assert(ret == 0);
  }
  return true;
}
예제 #27
0
파일: idlabel.cpp 프로젝트: liangjs/marktex
bool _check_idlabel_title(istream &s, string &title)
{
    title.clear();
    if (!s.good())
        return false;
    bool hv = false;
    while (1)
    {
        string line0;
        getline(s, line0);
        if (!allSpace(line0))
        {
            string line = removeLeadSpace2(line0);
            if (line.length() <= 1 || !(
                        (line.front() == '"' && line.back() == '"')
                        || (line.front() == '\'' && line.back() == '\'')
                        || (line.front() == '(' && line.back() == ')')
                    ))
            {
                if (!s.eof())
                    s.putback('\n');
                s.clear();
                strputback(s, line0);
                return hv;
            }
            title = line.substr(1, line.length() - 2);
            return true;
        }
        if (s.eof() || hv)
            break;
        hv = true;
    }
    return true;
}
void printStats(istream &in)
{
	//Output the number of edges to stdout.
	while (in.good())
	{
		string line;

		getline(in, line);

		while (!line.empty() && isspace(line[0])) line.erase(0, 1);

		if (line.length() < 2) continue;
		if (line[0] == '%') continue;

		//Print header information.
		istringstream sline(line);
		long a = 0, b = 0, c = 0;

		sline >> a >> b >> c;
		cout << b;
		return;
	}

	cerr << "No header information!" << endl;
	throw std::exception();
}
예제 #29
0
/**
 * @brief Gets a line of text from an input stream     
 *
 * @details Gets a line of text from an input stream
 *        up to a specified character, 
 *        or a specified length (-1 to allow for the null char);
 *        ending character is not placed in the string
 *          
 * @param in: istream object
 * @param in: specified length
 * @param in: specified ending character
 * @param out: string
 *
 * @note resolution for redirected input, getline did not work
 */
bool getLine( istream &consoleIn, char *str, int length, char stopChar )
   {
    const char LOWEST_PRINTABLE_CHAR = 32;  // space
    const char HIGHEST_PRINTABLE_CHAR = 126;  // tilde 
    int index = 0;
    int inVal;
    bool istreamState = consoleIn.good();

    inVal = consoleIn.get();

    while( char( inVal ) != stopChar && index < length - 1  )
       {
        if( inVal >= LOWEST_PRINTABLE_CHAR 
                                    && inVal <= HIGHEST_PRINTABLE_CHAR )
           {
            str[ index ] = char( inVal );

            index++;

            str[ index ] = NULL_CHAR;
           }

        inVal = consoleIn.get();
       }

    return istreamState;
   }
예제 #30
0
파일: Frond.C 프로젝트: jsgf/frond
void Frond::load(FrondGroup *group, istream &in)
{
	string line;
	float x, y;

	in >> x;
	in >> y;

	move(coord_t(x, y));

	setEnable(true);

	for(;;) {
		int id = -1;

		in >> id;

		if (!in.good() || id == -1) {
			in.clear();
			break;
		}

		Frond *p = group->getFrond(id);

		if (p == NULL) {
			p = new Frond(id, NULL);
			group->addFrond(p);
		}

		addPeer(p);
	}
}