Пример #1
0
/*
*	go to the next header
*/
bool FileIO::GotoHeader(char* header)
{
	//check for errors
	if ((this->mFileHandle == NULL) || (!header))
		return false;

	bool found = false;
	long headerSize = strlen(header);
	char* currentHeader = new char[headerSize];

	for(;;)
	{
		//go to a byte
		if (Mode() == RECORD_MODE)
		{
			//goto next unit
			if (!GotoNext())
				break;	//if there is no further unit
		}

		//reset current header
		memset(currentHeader, 0, headerSize);

		//there is a byte, find the correct bytes (header)
		for(;;)
		{
			//continue search if in BYTE_MODE and there is something to read
			if ((Mode() == RECORD_MODE) ||
				(EndOfFile()))
				break;

			//append one byte to the back of the current header
			for (int c=0; c<headerSize - 1; c++)
				currentHeader[c] = currentHeader[c+1];
			currentHeader[headerSize - 1] = PopByte();

			//continue search if the current header is not full or
			//	it's full but doesn't match the right header
			if (!currentHeader[0] || memcmp(currentHeader, header, headerSize))
				continue;
			else
			{
				found = true;
				break;
			}
		}

		//called break above -> check if found or finished by EOF
		if (found || EndOfFile())
			break;
	}

	//clean up memory
	if (currentHeader)
		delete currentHeader;

	//found header?
	return found;
}
Пример #2
0
JsonNode JsonReader::ParseObject() {

   JsonNode object = JsonNode(JsonNode::Type::Object);
   bool end = false;

   if (*m_data == '{') m_data++;

   /* Look for the next key name */
   while (!end) {

      std::string key;

      /* Look for string quotes */
      while (*m_data != '\"' && *m_data != '\'' && !EndOfFile()) m_data++;

      if (EndOfFile()) {
         PrintError("Syntax Error : '\"' , ''' were expected. ");
         break;
      }

      /* Parse the key as string */
      key = ParseString();

      SkipUntil(':');

      if (EndOfFile()) {
         PrintError("Syntax Error : ':' was expected. ");
         break;
      }

      m_data++;

      object[key] = this->ParseValue();

      while (*m_data != ',' && *m_data != '}' && !EndOfFile()) m_data++;

      switch (*m_data) {

         case ',':

            m_data++;
            break;

         case '}':

            end = true;
            m_data++;
            break;

         default:

            PrintError("Syntax Error : ',' , '}' were expected. ");
            end = true;
            break;
      };
   }

   return object;
}
Пример #3
0
 uint8_t read_uint8(std::ifstream &file)
 {
     char byte;
     file.read(&byte, 1);
     if (file.eof()) throw EndOfFile();
     return static_cast<uint8_t>(byte);
 }
Пример #4
0
static int8_t Rd_GetC_m (
    Rd_cl   *self )
{
    RAISE_Rd$EndOfFile();

    return 0;
}
Пример #5
0
/*
*	get total record from file,
*	byteRecord must be large enough to hold the data
*/
bool FileIO::PopRecord(void* byteRecord)
{
	//check for errors
	if ((this->mCurrentMode != RECORD_MODE) || !byteRecord ||
		(this->mFileHandle == NULL) ||
		EndOfFile())
		return false;

	//if PopRecordSize has not been called
	PopRecordSize();

	if (!mRecordSize)
		return false;

	//read Record
	int rval;
	rval = fread(byteRecord, 1, mRecordSize, this->mFileHandle);

	//check for errors
	if (rval != mRecordSize)
		return false;

	//initialize other attributes
	mRecordSize = 0;

	DetermineNextMode();

	return true;
}
Пример #6
0
static int8_t Rd_GetC_m (
        Rd_cl   *self )
{
    Pipe_st *st = self->st;
    uint8_t c;
    uint64_t nb;

    rd_enter(st);

    if (st->ungetc) {
	c=st->lastc;
	st->ungetc=False;
	nb=1;
    } else {
	nb=rd_get(st, &c, 1, False);
    }

    MU_RELEASE(&st->mu);
    if (nb==0) {
	MU_RELEASE(&st->rd_mu);
	RAISE_Rd$EndOfFile();
    }
    st->lastc=c;
    MU_RELEASE(&st->rd_mu);
    return c;
}
Пример #7
0
JsonNode JsonReader::ParseArray() {

   JsonNode object = JsonNode(JsonNode::Type::Array);
   bool end = false;

   /* Verify we're parsing an array */
   if (*m_data == '[') m_data++;

   while (!end) {

      /* Use the index value as the key name */
      object[object.ChildCount()] = this->ParseValue();

      while (*m_data != ',' && *m_data != ']' && !EndOfFile()) m_data++;

      switch (*m_data) {

         case ',':
            m_data++;
            break;

         case ']':
            end = true;
            m_data++;
            break;

         default:
            PrintError("Syntax Error : ',' , ']' were expected. ");
            end = true;
            break;
      };
   }

   return object;
}
Пример #8
0
void
Read_ENV2(GMC_ARG_VOID)
{
   tps_FileName FileName;
   tp_FilDsc FilDsc;
   tps_Str StrBuf;
   tp_Str Str;
   int count, status;
   size_t sz;

   sz = snprintf(FileName, MAX_FileName, "%s/ENV2", OdinDirName);
   if (sz >= MAX_FileName) {
      (void)fprintf(stderr, "File name too long (MAX_FileName=%d): %s/ENV2\n",
		  MAX_FileName, OdinDirName);
      exit(1); }/*if*/;
   FilDsc = FileName_RFilDsc(FileName, FALSE);
   FORBIDDEN(FilDsc == ERROR);
   for (count = fscanf((FILE *)FilDsc, "%[^\1]\1\n", StrBuf);
	count == 1;
	count = fscanf((FILE *)FilDsc, "%[^\1]\1\n", StrBuf)) {
      Str = Malloc_Str(StrBuf);
      status = putenv(Str);
      FORBIDDEN(status != 0); }/*for*/;
   FORBIDDEN(!EndOfFile(FilDsc));
   Close(FilDsc);
   }/*Read_ENV2*/
Пример #9
0
 uint16_t read_uint16(std::ifstream &file)
 {
     char bytes[2];
     file.read(bytes, 2);
     if (file.eof()) throw EndOfFile();
     uint16_t value = static_cast<unsigned char>(bytes[0]) | (static_cast<unsigned char>(bytes[1]) << 8);
     return value;
 }
Пример #10
0
T ReadNext(std::istream& stream, int& line)
{
  std::string s;
  ReadNextToken(stream, s, line);
  if (s == "")
    throw EndOfFile();
  return ParseType<T>(s);
}
Пример #11
0
inline std::string ReadNext<std::string>(std::istream& stream, int& line)
{
  std::string s;
  ReadNextToken(stream, s, line);
  if (s == "")
    throw EndOfFile();
  return s;
}
Пример #12
0
 int16_t read_int16(std::ifstream &file)
 {
     char bytes[2];
     file.read(bytes, 2);
     if (file.eof()) throw EndOfFile();
     int16_t value = bytes[0] | (bytes[1] << 8);
     return value;
 }
Пример #13
0
	char Parser::NeedChar() const
	{
		if (AtEnd())
		{
			throw EndOfFile();
		}

		return GetChar();
	}
Пример #14
0
bool StringSearch_c::DoSearch ()
{
	Assert ( m_pFile );

	int nBytesToRead = READ_BUFFER_SIZE;
	int iBufStart = 0;

	if ( m_iNextOffset > 0 )
		fseek ( m_pFile, m_iNextOffset, SEEK_CUR );
	else
		if ( m_iNextOffset < 0 )
		{
			nBytesToRead += m_iNextOffset * 2;
			iBufStart -= m_iNextOffset * 2;
		}

	int nBytesRead = fread ( m_dBuffer + iBufStart, 1, nBytesToRead, m_pFile );
	if ( nBytesRead < nBytesToRead )
		m_bEndReached = true;

	int iTestOffset = m_iNextOffset == 0 ? 0 : 1;
	
	if ( Test ( (wchar_t *)m_dBuffer + iTestOffset, nBytesRead / 2, m_iNextOffset ) )
	{
		EndOfFile ();
		return true;
	}

	if ( ! m_bEndReached )
	{
		--m_iNextOffset;
		if ( m_iNextOffset < 0 )
		{
			for ( int i = 0; i < -m_iNextOffset; ++i )
				m_dBuffer [i] = m_dBuffer [nBytesRead + m_iNextOffset + i];
		}
	}
	else
		EndOfFile ();

	return false;
}
Пример #15
0
 void read_string(std::ifstream &file)
 {
     // TODO
     char byte;
     for(;;)
     {
         file.read(&byte, 1);
         if (file.eof()) throw EndOfFile();
         if (byte == '\0')
             break;
     }
 }
Пример #16
0
 uint32_t read_uint32(std::ifstream &file)
 {
     char bytes[4];
     file.read(bytes, 4);
     if (file.eof()) throw EndOfFile();
     uint32_t a = static_cast<unsigned char>(bytes[0]);
     uint32_t b = static_cast<unsigned char>(bytes[1]) << 8;
     uint32_t c = static_cast<unsigned char>(bytes[2]) << 16;
     uint32_t d = static_cast<unsigned char>(bytes[3]) << 24;
     uint32_t value = a | b | c | d;
     return value;
 }
Пример #17
0
	void Parser::SkipCharClass2(const CharClass & charClass)
	{
		while (NotAtEnd())
		{
			if (!charClass.Contains(GetChar()))
			{
				return;
			}

			Advance();
		}

		throw EndOfFile();
	}
Пример #18
0
	void Parser::WaitChar(char c)
	{
		while (NotAtEnd())
		{
			if (GetChar() == c)
			{
				return;
			}

			Advance();
		}

		throw EndOfFile();
	}
Пример #19
0
	void Parser::SkipChars(char c)
	{
		while (NotAtEnd())
		{
			if (GetChar() != c)
			{
				return;
			}

			Advance();
		}

		throw EndOfFile();
	}
Пример #20
0
bool
LogCatReader::OnFileEvent(int _fd, unsigned mask)
{
  assert(_fd == fd.Get());

  char buffer[1024];
  ssize_t nbytes = fd.Read(buffer, sizeof(buffer));
  if (nbytes > 0) {
    if (data.length() < 1024 * 1024)
      data.append(buffer, nbytes);
    return true;
  } else {
    EndOfFile();
    return false;
  }
}
Пример #21
0
bool CPipedCMD::HasData()
{
    if (EndOfFile())
        return false;
                    
    int ret = poll(&m_PollData, 1, 10);
    
    if (ret == -1) // Error occured
        throw Exceptions::CExPoll(errno);
    else if (ret == 0)
        return false;
    else if (((m_PollData.revents & POLLIN) == POLLIN) || ((m_PollData.revents & POLLHUP) == POLLHUP))
        return true;
    
    return false;
}
Пример #22
0
I NRLib::ReadAsciiArrayFast(std::istream& stream, I begin, size_t n)
{
  for (size_t i = 0; i < n; ++i) {
    stream >> *begin;
    ++begin;
    if ( stream.eof() ) {
      throw EndOfFile();
    }
    if ( stream.fail() ) {
      stream.clear();
      std::string nextToken;
      stream >> nextToken;
      throw Exception("Failure during reading element " + ToString(static_cast<unsigned int>(i)) + " of array. "
        + "Next token is " + nextToken + "\n");
    }
  }
Пример #23
0
/*
*	determine next mode
*/
bool FileIO::DetermineNextMode()
{
	if ((this->mFileHandle == NULL) ||
		EndOfFile())
		return false;

	int rval;
	rval = fread(&this->mCurrentMode, 1, 1, this->mFileHandle);

	//just use the last byte
	if ((this->mCurrentMode != BYTE_MODE) && (this->mCurrentMode != RECORD_MODE))
		this->mCurrentMode = BYTE_MODE;

	if (rval != 1)
		return false;

	return true;
}
Пример #24
0
int
my_yyparse(void)
{
  if (interactive_mode)
    {
      char *line = NULL;
      char buffer[1024];
      snprintf(buffer, 1024, "mini_shell(%d):", status);
      line = readline(buffer);
      if(line != NULL)
	{
	  int ret;
	  add_history(line);              // Enregistre la line non vide dans l'historique courant
	  *strchr(line, '\0') = '\n';      // Ajoute \n à la line pour qu'elle puisse etre traité par le parseur
	  ret = yyparse_string(line);     // Remplace l'entrée standard de yyparse par s
	  free(line);
	  return ret;
	}
      else
	{
	  EndOfFile();
	  return -1;
	}
    }
  else
    {
      // pour le mode distant par exemple
      
      int ret; int c;
          
      char *line = NULL;
      size_t linecap = 0;
      ssize_t linelen;
      linelen = getline(&line, &linecap, stdin);

      if(linelen>0)
	{
	  int ret;
	  ret = yyparse_string(line);  
	  free(line);
	  return ret;
	}    
    }
}
Пример #25
0
Any JsonReader::ParseNumber() {

   char *start = m_data;
   Any number_value;
   char last_char;

   bool foundcomma = false;

   if (*m_data == '-') m_data++;

   while (!EndOfFile()) {

      if ((*m_data >= '0' && *m_data <= '9')) {
         m_data++;
      } else if (*m_data == '.') {

         if (foundcomma) {
            PrintError("Syntax Error: Expected a number");
            break;
         } else {
            foundcomma = true;
            m_data++;
         }

      } else {
         break;
      }
   }

   last_char = *m_data;
   *m_data = '\0';

   if (foundcomma) {
      number_value = Any(std::strtod(start, nullptr));
   } else {
      number_value = (m_data - start > 4) ? Any(std::strtol(start, nullptr, 10))
                                          : Any(std::stoi(start, nullptr, 10));
   }

   *m_data = last_char;

   return number_value;
}
Пример #26
0
/*
*	get record size if in RECORD_MODE
*/
unsigned int FileIO::PopRecordSize()
{
	//check for errors
	if (this->mCurrentMode != RECORD_MODE ||
		(this->mFileHandle == NULL) ||
		EndOfFile())
		return 0;

	//if PopRecordSize has already been called
	if (mRecordSize)
		return mRecordSize;

	//read RecordSize
	int rval;
	rval = fread(&mRecordSize, 1, sizeof(unsigned int), this->mFileHandle);

	if (rval == sizeof(unsigned int))
		return mRecordSize;

	return 0;
}
Пример #27
0
static int8_t Rd_LGetC_m (
        Rd_cl   *self )
{
    Pipe_st *st = self->st;
    uint8_t c;
    uint64_t nb;

    if (st->ungetc) {
	c=st->lastc;
	st->ungetc=False;
	nb=1;
    } else {
	MU_LOCK(&st->mu);
	nb=rd_get(st, &c, 1, False);
	MU_RELEASE(&st->mu);
    }

    if (nb==0) {
	RAISE_Rd$EndOfFile();
    }
    st->lastc=c;
    return c;
}
Пример #28
0
/*
*	get next byte if in BYTE_MODE
*	returns 0 if not in BYTE_MODE or another error occured
*/
unsigned char FileIO::PopByte()
{
	//check for errors
	if (this->mCurrentMode != BYTE_MODE ||
		(this->mFileHandle == NULL) ||
		EndOfFile())
		return 0;

	unsigned char currentByte;
	int rval;
	rval = fread(&currentByte, 1, 1, this->mFileHandle);

	//initialize other attributes
	mRecordSize = 0;

	//check for errors
	if (rval != 1)
		return 0;

	DetermineNextMode();

	return currentByte;
}
Пример #29
0
STATUSCODE
ParseFile(
    PPARSERDATA pParserData,
    PWSTR       pFilename
    )

/*++

Routine Description:

    Parse a PCL-XL printer description file

Arguments:

    pParserData - Points to parser data structure
    pFilename - Specifies the name of the file to be parsed

Return Value:

    ERR_NONE if successful, error code otherwise

--*/

{
    STATUSCODE  status;
    PFILEOBJ    pFile;
    INT         syntaxErrors;

    //
    // Map the file into memory for read-only access
    //

    Verbose(("File %ws\n", pFilename));

    if (! (pFile = CreateFileObj(pFilename)))
        return ERR_FILE;

    pParserData->pFile = pFile;

    //
    // Compute the 16-bit CRC checksum of the file content
    //

    pParserData->checksum = 
        ComputeCrc16Checksum(pFile->pStartPtr, pFile->fileSize, pParserData->checksum);

    //
    // Process entries in the file
    //

    while ((status = ParseEntry(pParserData)) != ERR_EOF) {

        if (status != ERR_NONE && status != ERR_SYNTAX) {
    
            DeleteFileObj(pFile);
            return status;
        }
    }

    if (EndOfFile(pFile) && !EndOfLine(pFile)) {

        Warning(("Incomplete last line ignored.\n"));
    }

    //
    // Unmap the file and return to the caller
    //

    syntaxErrors = pFile->syntaxErrors;
    DeleteFileObj(pFile);

    if (syntaxErrors > 0) {

        Error(("%d syntax error(s) found in %ws\n", syntaxErrors, pFilename));
        return ERR_SYNTAX;
    }

    return ERR_NONE;
}
Пример #30
0
TreeNode* Parser::Statement()
{
	kdDebug(0)<<"Parser::Statement()"<<endl;
	while (currentToken.type == tokEOL) getToken(); // statements can allways start on newlines
	switch (currentToken.type)
	{
		case tokLearn         : return Learn();            break;

		case tokIf            : return If();               break;
		case tokFor           : return For();              break;
		case tokForEach       : return ForEach();          break;
		case tokWhile         : return While();            break;
		case tokRun           : return ExternalRun();      break;
		case tokReturn        : return Return();           break;
		case tokBreak         : return Break();            break;
		case tokUnknown       : return Other();            break; //assignment or function call

		case tokClear         : return Clear();            break;
		case tokGo            : return Go();               break;
		case tokGoX           : return GoX();              break;
		case tokGoY           : return GoY();              break;
		case tokForward       : return Forward();          break;
		case tokBackward      : return Backward();         break;
		case tokDirection     : return Direction();        break;
		case tokTurnLeft      : return TurnLeft();         break;
		case tokTurnRight     : return TurnRight();        break;
		case tokCenter        : return Center();           break;
		case tokSetPenWidth   : return SetPenWidth();      break;
		case tokPenUp         : return PenUp();            break;
		case tokPenDown       : return PenDown();          break;
		case tokSetFgColor    : return SetFgColor();       break;
		case tokSetBgColor    : return SetBgColor();       break;
		case tokResizeCanvas  : return ResizeCanvas();     break;
		case tokSpriteShow    : return SpriteShow();       break;
		case tokSpriteHide    : return SpriteHide();       break;
		case tokSpritePress   : return SpritePress();      break;
		case tokSpriteChange  : return SpriteChange();     break;

		case tokPrint         : return Print();            break;
		case tokInputWindow   : return InputWindow();      break;
		case tokMessage       : return Message();          break;
		case tokFontType      : return FontType();         break;
		case tokFontSize      : return FontSize();         break;
		case tokRepeat        : return Repeat();           break;
		case tokRandom        : return Random();           break;
		case tokWait          : return Wait();             break;
		case tokWrapOn        : return WrapOn();           break;
		case tokWrapOff       : return WrapOff();          break;
		case tokReset         : return Reset();            break;
		
		case tokEOF           : return EndOfFile();        break;
		
		case tokEnd           : Error(currentToken, i18n("Cannot understand ']'"), 1050);
		                        getToken();
		                        return new TreeNode(currentToken, Unknown);
		                        break;

		case tokBegin         : Error(currentToken, i18n("Cannot understand '['"), 1050);
		                        getToken();
		                        return new TreeNode(currentToken, Unknown);
		                        break;

		default               : break;
	}
	if (currentToken.type != tokEnd)
	{
		Error(currentToken, i18n("Cannot understand '%1'").arg(currentToken.look), 1060);
	}

	getToken();
	return new TreeNode(currentToken, Unknown); // fall-though for unknowns
}