Beispiel #1
0
static BOOL HandleSubstitution()
{
BOOL done = FALSE;
int LineNo = 0;
char *FixedLine;
BOOL HadChanges = FALSE;

/* now process the file */
while ( !done )
	{
	if ( ReadLine( ) != 0 )
		done = TRUE;
	else
		{
		++LineNo;
		/*
		TracePrintf( "HandleSubstitution: Processing Line %d\n", LineNo );
		*/
		FixedLine = XTL_Substitute( LineBuffer );
		
		if ( FixedLine == NULL )  /* Bad things happened */
			ErrorExit( "HandleSubstitution() Line blew up" );
		
		if ( ! HadChanges )
		{
			if ( strcmp( FixedLine, LineBuffer ) != 0 )
				HadChanges = TRUE;
		}
	
		WriteToOutputBuffer( FixedLine, strlen(FixedLine) );		
		FreeMemoryBlock( FixedLine );
		}
	}

	
printf( "HandleSubstitution: Processed %d lines for substitution processing this pass\n", LineNo );

return HadChanges;

}
Beispiel #2
0
static void WriteOutputFile( char *OutputFileName )
{
	FILE *Out;
	int num;
	XTL_FileStatus XTLFileStat;
	
	
	printf( "Checking to see if we need to make the directory for the output file %s\n", OutputFileName );
	MakeDirChainForFile( OutputFileName );
	
	printf( "Opening output file %s - ", OutputFileName );

	/* now write the actual output file */
	Out = fopen( OutputFileName, "w+");
	if ( Out == NULL )
		ErrorExit( "Failed to open output file" );

	puts( "Writing file header data" );

	if ( strlen( FileForOutputHeader ) > 0 )  /* if we have a fileheader */
	{
		if ( XTL_CopyFileContents( FileForOutputHeader, Out) != 0 )
			ErrorExit( "Unable to copy FileForOutputHeader" );
	}

	puts( "Writing actual file data" );

	/* DANA - FIXUP */
	while ( ReadLine( ) == 0 )
	{	
	num = fwrite(LineBuffer, 1, strlen(LineBuffer), Out );
	}
	
	if ( !QuestionsOnly	 )  /* if the user requested we include the document structure stuff intact */
		fputs( "\\end{document}", Out ); /* write the end document line */

	fclose(Out);
	puts( "output file complete" );

}
Beispiel #3
0
/*****************************************
ProcessPairs(): Process pairs of names.
Format: dest src
*****************************************/
void ProcessPairs(FILE* Fin, char* Type)
{
  char Buf[10240];
  char Dst[FILENAME_MAX];
  char Src[FILENAME_MAX];
  int Space;
  int i, s, c;

  while (ReadLine(Fin, Buf, sizeof(Buf)) > 0)
  {
    Space = 0;
    /* save the dst name */
    while ((Buf[Space] != '\0') && (Buf[Space] != ' ')) Space++;
    strncpy(Dst, Buf, Space);
    /* skip the space */
    /* save the src name and remove unicode stuff */
    memset(Dst, '\0', sizeof(Dst));
    memset(Src, '\0', sizeof(Src));
    strncpy(Dst, Buf, Space);
    s = 0;
    for (i = Space + 1; Buf[i] != '\0'; i++)
    {
      if (Buf[i] != '&') Src[s++] = Buf[i];
      else
      {
        c = UnUnicodeHex(Buf + i);
        if (c >= 0)
        {
          Src[s++] = c;
          i += 5;
        }
        else Src[s++] = Buf[i];
      }
    }
#if 0
    printf("Dst='%s'  Src='%s'\n",Dst,Src);
#endif
    CopyFile(Src, Type, Dst);
  }
} /* ProcessPairs() */
Beispiel #4
0
static int ProgramMode(int adx, int argc, FChS * argv[])
{
    FAssert(adx < argc);

    FObject nam = MakeStringS(argv[adx]);

    adx += 1;
    R.CommandLine = MakePair(MakeInvocation(adx, argv), MakeCommandLine(argc - adx, argv + adx));

    FObject port;
    {
        FDontWait dw;

        port = OpenInputFile(nam);
        if (TextualPortP(port) == 0)
        {
#ifdef FOMENT_WINDOWS
            printf("error: unable to open program: %S\n", argv[adx - 1]);
#endif // FOMENT_WINDOWS

#ifdef FOMENT_UNIX
            printf("error: unable to open program: %s\n", argv[adx - 1]);
#endif // FOMENT_UNIX
            return(Usage());
        }
    }

    FCh ch;

    // Skip #!/usr/local/bin/foment

    if (PeekCh(port, &ch) && ch == '#')
        ReadLine(port);

    FObject proc = CompileProgram(nam, port);

    ExecuteThunk(proc);
    ExitFoment();
    return(0);
}
Beispiel #5
0
bool NntpConnection::Connect()
{
    debug("Opening connection to %s", GetHost());

    if (m_status == csConnected)
    {
        return true;
    }

    if (!Connection::Connect())
    {
        return false;
    }

    char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr);

    if (!answer)
    {
        ReportErrorAnswer("Connection to %s (%s) failed: Connection closed by remote host", nullptr);
        Disconnect();
        return false;
    }

    if (strncmp(answer, "2", 1))
    {
        ReportErrorAnswer("Connection to %s (%s) failed: %s", answer);
        Disconnect();
        return false;
    }

    if ((strlen(m_newsServer->GetUser()) > 0 && strlen(m_newsServer->GetPassword()) > 0) &&
            !Authenticate())
    {
        return false;
    }

    debug("Connection to %s established", GetHost());

    return true;
}
Beispiel #6
0
inline
bool
TxtHandler::TestLine(const wxString & test, bool strip)
{
    // Only strip this line for the test.  In case whitespace characters are
    // meaningful, we should preserve them if we have to UngetLine().
    wxString line = ReadLine(NO_STRIP_WHITESPACE);

    if (strip == true)
    {
        if (line.Trim(true).Trim(false) == test)
            return true;
    }
    else
    {
        if (line == test)
            return true;
    }

    UngetLine(line);
    return false;
}
/*******************************************************************
 * Function Name: Read
 * Return Type 	: int
 * Created On	: Feb 26, 2013
 * Created By 	: hrushi
 * Comments		: Reads the feature file into the memory
 * Arguments	: const Args& args
 *******************************************************************/
int Features::Read( const Args& args)
{
	string line;
	unsigned int LineCount = 0;

	if( fPtr.is_open() )
	{
		while(fPtr.good())
		{
			getline(fPtr, line);
			LineCount++;

			try
			{
				ReadLine(args, line);
			}
			catch( int Err )
			{
				cerr << "Check Line Number: " << LineCount << endl;
				throw Err;
			}
		}

		ZMUL(args);
	}
	else
	{
		cerr << "Cannot read Feature File " << endl;
		exit(ERR_CANNOT_OPEN_FILE);
	}

	if( ImgFeature.size() == 0 )
	{
		cerr << "No feature read from " << FilePath.string() << endl;
		throw ERR_CANNOT_READ_VALUE;
	}

	return EXIT_SUCCESS;
}
Beispiel #8
0
bool CDialogLoaderMK2::ProcessScript(CDialogScript* pScript, const XmlNodeRef& node)
{
	CDialogScript::SScriptLine scriptLine;

	const char* scriptID = pScript->GetID();
	string desc = node->getAttr("Description");
	pScript->SetDescription(desc);

	for (int i=0; i<node->getChildCount(); ++i)
	{
		XmlNodeRef lineNode = node->getChild(i);
		if (lineNode && lineNode->isTag("Line"))
		{
			ResetLine(scriptLine);
			if (ReadLine (lineNode, scriptLine, scriptID, i) == true)
			{
				pScript->AddLine(scriptLine);
			}
		}
	}
	return true;
}
// Load an .obj file into Manta
model* FileManager_Model::LoadObj(string filename, vec3* objPosition)
{
	byte* buffer;
	byte  lineBuffer[MAX_FILE_LINE_LENGTH];
	bool  reachedEnd = false;
	byte* position;

	if (LoadFile(&buffer, filename))
	{
		int vertexCount = 0;
		int polyCount = 0;
		// Set vertex offset (-1 since obj is indexed from 1)
		vertexOffset = scene->getVertexCount() - 1;
		polyOffset = scene->getPolyCount();
		// Loop through each line
		position = buffer;
		while (!reachedEnd)
		{
			reachedEnd = ReadLine(&position, lineBuffer);
			switch (lineBuffer[0])
			{
				case 'v':
					vertexCount++;
					LoadObj_AddVertex(lineBuffer);
					break;
				case 'f':
					polyCount++;
					LoadObj_AddPolygon(lineBuffer);
					break;
				default:
//					printf("-- Skipping line --\n");
					break;
			}
		}
		free(buffer);
		return scene->addModel(objPosition, vertexOffset+1, vertexCount, polyOffset, polyCount);
	}
	return NULL;
}
Beispiel #10
0
bool ReplayLogger::ReadPoint(double *Time,
			     double *Latitude,
			     double *Longitude,
			     double *Altitude)
{
  TCHAR buffer[200];
/*
  // This is creating problems with the interpolator and calculations based on differential times
  // such as variometer derived from altitude differences. Probably due to vario lowpass filters.
  while(ReadLine(buffer)) {
    if(ScanBuffer(buffer, Time, Latitude, Longitude, Altitude))
      return true;
  }
  return false;
*/
  bool found=false;
  while(ReadLine(buffer) &&!found) {
    if(ScanBuffer(buffer, Time, Latitude, Longitude, Altitude))
      found=true;
  }
  return found;
}
Beispiel #11
0
char* FileReader::ReadFile()
{
	if (!file || file->eof())
	{
		return nullptr;
	}
	char* file = new char[1];
	file[0] = '\0';

	while (char* line = ReadLine())
	{
		char* temp = new char[strlen(file) + strlen(line) + 2];
		Copy(temp, file, strlen(file));
		Copy(temp + strlen(file), line, strlen(line));
		Copy(temp + strlen(temp), "\n", 1);
		delete[] file;
		delete[] line;
		file = temp;
	}

	return file;
}
Beispiel #12
0
void loop() {
	  //put your main code here, to run repeatedly: 
	delay(1000);
        
        //rundiagnostic();
	
        //rundiagnostic();
	utrasonic_espi.getReadings(es);
	//Serial.println(es.ultrasonic0); 
        
	printf("%d %d %d %d\n", es.ultrasonic0, es.ultrasonic90, es.ultrasonic180, es.ultrasonic270);
	
        struct Map* beliefs;
	
	beliefs = new_map();

         // debug - need to add defensive code that means function poitners are all valid prior to entry into function
	 struct Actn action = collision_avoidance_str(beliefs, 0, 0, 0, TURN_PROBABILITY);// 0% prob of turn
	 //printf("Action is 1  %d with magnitude 10 %d\n", action.c, action.m);
         if(action.c == MOVE) {
	   printf("forward %d cm\n", action.m);
         } else if(action.c == TURN) {
           printf("turn %d deg\n",action.m);
         } else if(action.c == NOP) {
           printf("NOP\n");
         } else {
           printf("dunno\n");
         }

         char inputdata[20];
         Serial.println("done\n");

         ReadLine(inputdata); 

         Serial.println("you clicked\n");

	 Serial.flush();
}
Beispiel #13
0
bool NntpConnection::AuthInfoUser(int recur)
{
    if (recur > 10)
    {
        return false;
    }

    WriteLine(BString<1024>("AUTHINFO USER %s\r\n", m_newsServer->GetUser()));

    char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr);
    if (!answer)
    {
        ReportErrorAnswer("Authorization for %s (%s) failed: Connection closed by remote host", nullptr);
        return false;
    }

    if (!strncmp(answer, "281", 3))
    {
        debug("Authorization for %s successful", GetHost());
        return true;
    }
    else if (!strncmp(answer, "381", 3))
    {
        return AuthInfoPass(++recur);
    }
    else if (!strncmp(answer, "480", 3))
    {
        return AuthInfoUser(++recur);
    }

    if (char* p = strrchr(answer, '\r')) *p = '\0'; // remove last CRLF from error message

    if (GetStatus() != csCancelled)
    {
        ReportErrorAnswer("Authorization for %s (%s) failed: %s", answer);
    }
    return false;
}
Beispiel #14
0
int CFCMReadFile::GetNumberColums(CString szDelimiter)
{
	int nCol = 0;
	int iPos(0), iFound;
	CString szline;

	if (ReadLine(szline))
	{
		ResetFilePointer();

		// Format data: A, B, C
	
		if (szline.IsEmpty()) { return 0; }

		while ((iFound = szline.Find(szDelimiter, iPos)) != -1)
		{
			++nCol;
			iPos = iFound + 1;
		}
	}

	return (nCol + 1);
}
Beispiel #15
0
bool CFCMReadFile::ParsingTextFile(CString szDelimiter)
{
    if(!IsOpen())
    {
        return false;
    }

    CString szLine;

    ResetData();
    m_nCols = GetNumberColums(szDelimiter);

    while(!Eof())
    {
        if(ReadLine(szLine))
        {
            ++m_nRows;
            ParsingLine(szLine, szDelimiter);
        }
    };

    return true;
}
Beispiel #16
0
int main (int argc, const char * argv[])
{
    char line[ kMaxLineLength+1 ];  // room for kMaxLineLength chars + one NUL
    int	 numWords;
    
    // Chapter 9 exercise:
    //  Removed the code that prompts for a line.
    
    // Chapter 9 exercise:
    //  Run ReadLine() and CountWords() in a while loop that continues, indefinately,
    //  until ReadLine() returns false (meaning there are no more characters to read).
    //  Note: Becuase of this, the program will now run in the Xcode console until you
    //        stop it with the Stop button, or type Control+D in the console pane.
    //        ^D is the ASCII end-of-file control character and will cause standard in
    //        to return an EOF.
    while ( ReadLine( line ) != false ) {
        numWords = CountWords( line );
        printf( "\n---- This line has %d word%s. ---\n", numWords, ( numWords!=1 ? "s" : "" ) );
        printf( "%s\n", line );
    }
    
    return 0;
}
Bool_t KVSimReader_MMM::ReadEvent()
{

   evt->Clear();
   Int_t mult = 0, natt = 0;

   ReadLine(" ");

   Int_t res = GetNparRead();
   switch (res) {
      case 0:
         Info("ReadEvent", "case 0 line est vide");
         return kFALSE;
      default:
         idx = 0;
         mult = GetIntReadPar(idx++);
         natt = 6 * mult + 4 + 1;
         if (natt != res) {
            Info("ReadEvent", "Nombre de parametres (%d) different de celui attendu (%d)", res, natt);
            return kFALSE;
         }
         evt->GetParameters()->SetValue("Eth", GetDoubleReadPar(idx++));
         evt->GetParameters()->SetValue("Eclb", GetDoubleReadPar(idx++));
         evt->GetParameters()->SetValue("Eexci", GetDoubleReadPar(idx++));
         evt->GetParameters()->SetValue("Ebind", GetDoubleReadPar(idx++));

         for (Int_t mm = 0; mm < mult; mm += 1) {
            nuc = (KVSimNucleus*)evt->AddParticle();
            ReadNucleus();
         }

         evt->SetNumber(nevt);
         nevt += 1;
         return kTRUE;
   }

}
Beispiel #18
0
bool NNTPConnection::AuthInfoPass(int iRecur)
{
	if (iRecur > 10)
	{
		return false;
	}

	char tmp[1024];
	snprintf(tmp, 1024, "AUTHINFO PASS %s\r\n", m_pNewsServer->GetPassword());
	tmp[1024-1] = '\0';

	WriteLine(tmp);

	char* answer = ReadLine(m_szLineBuf, CONNECTION_LINEBUFFER_SIZE, NULL);
	if (!answer)
	{
		ReportErrorAnswer("Authorization for server%i (%s) failed: Connection closed by remote host", NULL);
		return false;
	}
	else if (!strncmp(answer, "2", 1))
	{
		debug("Authorization for %s successful", GetHost());
		return true;
	}
	else if (!strncmp(answer, "381", 3))
	{
		return AuthInfoPass(++iRecur);
	}

	if (char* p = strrchr(answer, '\r')) *p = '\0'; // remove last CRLF from error message

	if (GetStatus() != csCancelled)
	{
		ReportErrorAnswer("Authorization for server%i (%s) failed (Answer: %s)", answer);
	}
	return false;
}
int
main(void)
{
    const OpenFileId INPUT  = CONSOLE_INPUT;
    const OpenFileId OUTPUT = CONSOLE_OUTPUT;
    char             line[MAX_LINE_SIZE];
    char            *argv[MAX_ARG_COUNT];

    for (;;) {
        WritePrompt(OUTPUT);
        const unsigned lineSize = ReadLine(line, MAX_LINE_SIZE, INPUT);
        if (lineSize == 0)
            continue;

        if (PrepareArguments(line, argv, MAX_ARG_COUNT) == 0) {
            WriteError("too many arguments.", OUTPUT);
            continue;
        }

        // Comment and uncomment according to whether command line arguments
        // are given in the system call or not.
        const SpaceId newProc = Exec(line);
        //const SpaceId newProc = Exec(line, argv);

        // TO DO: check for errors when calling `Exec`; this depends on how
        //        errors are reported.

        Join(newProc);
        // TO DO: is it necessary to check for errors after `Join` too, or
        //        can you be sure that, with the implementation of the system
        //        call handler you made, it will never give an error?; what
        //        happens if tomorrow the implementation changes and new
        //        error conditions appear?
    }

    return 0;  // Never reached.
}
Beispiel #20
0
  inline bool HasNext() {
    static const IterType end;
    if ( !cache_.empty() )
      return(true);
    if ( iter_ == end )
      return(false);

    /*
    Must ReadLine() in case padding is such that all remaining elements
      in a file vaporize.
    Example:
       chr1	20	100
       chr1	30	50
       chr2	5	8

      bedops -u --pad -5:-10
    */
    BedType* tmp = ReadLine();
    if ( tmp != static_cast<BedType*>(0) ) {
      PushBack(tmp);
      return(true);
    }
    return(false);
  }
Beispiel #21
0
int CTextFile::ReadLine(char* d, int max_len)
{
	char* pTemp = NULL;
	
	int size_read = ReadLine(&pTemp);

	if (size_read < 0) {
		free(pTemp);
		return -1;
	}
	
	if (size_read < max_len) {
		memcpy(d, pTemp, size_read);
	} else {
		memcpy(d, pTemp, max_len);
	}

	if (max_len > 0) {
		d[min(size_read, max_len-1)] = 0;
	} else {
		return (!size_read?-1:0);
	}

	if (max_len > 3) {
		if (GetOutputEncoding() == CharacterEncoding::UTF16LE) {
			d[min(size_read-1, max_len-2)] = 0;
			d[min(size_read-2, max_len-3)] = 0;
		}
	} else {
		memset(d, 0, max_len);
	}

	free(pTemp);

	return (min(max_len-1, size_read));
}
Beispiel #22
0
void HandleRequest(int clientID, __CSERVE_Session session){
    char* buffer = calloc(1, 512);
    
    int IsLoggedIn = false;
    
    for(;;){
        char** request = SplitRequest(ReadLine(session.sock),'/');
        
        if(strncmp(request[0],MoveRequest, strlen(MoveRequest)) == 0 && IsLoggedIn){
                sprintf(buffer, "M/%d/%s/%s/\n", clientID, request[1], request[2], request[3]);
                SendToAllClients(buffer, strlen(buffer));
                memset(buffer, 0, 512);
        } else if(strncmp(request[0],LoginRequest, strlen(MoveRequest)) == 0){
                sprintf(buffer, "L/1\n");
                write(session.sock, buffer, strlen(buffer));
                memset(buffer, 0, 512);
                IsLoggedIn = true;
        } else if(strncmp(request[0],SayRequest, strlen(MoveRequest)) == 0 && IsLoggedIn){
                sprintf(buffer, "S/%d/%s/\n", clientID, request[1]);
                SendToAllClients(buffer, strlen(buffer));
                memset(buffer, 0, 512);
        }
    }
}
Beispiel #23
0
void ParserGroup::Parse(filesystem::FB_FILE *fp)
{
	sub_groups = string_map();
	
	while(!feof(fp))
	{
		std::string string = ReadLine(fp);

		int position = IsProperty(string);
		if(position != -1)
		{
			std::string property = GetProperty(string, position, true);
			std::string value = GetProperty(string, position, false);

			properties[ property ] = value;
		}
		else
		{
			// Branches ?
			for(int i = 0; i < (int)string.size(); ++i)
			{
				if(string[i] == '{')
				{
					ParseSubGroups(fp);
					break;
				}

				if(string[i] == '}')
				{
					// End of this group
					return;
				}
			}
		}
	}
}
nsresult
nsAuthSambaNTLM::SpawnNTLMAuthHelper()
{
    const char* username = PR_GetEnv("USER");
    if (!username)
        return NS_ERROR_FAILURE;

    const char* const args[] = {
        "ntlm_auth",
        "--helper-protocol", "ntlmssp-client-1",
        "--use-cached-creds",
        "--username", username,
        nullptr
    };

    bool isOK = SpawnIOChild(const_cast<char* const*>(args), &mChildPID, &mFromChildFD, &mToChildFD);
    if (!isOK)  
        return NS_ERROR_FAILURE;

    if (!WriteString(mToChildFD, NS_LITERAL_CSTRING("YR\n")))
        return NS_ERROR_FAILURE;
    nsCString line;
    if (!ReadLine(mFromChildFD, line))
        return NS_ERROR_FAILURE;
    if (!StringBeginsWith(line, NS_LITERAL_CSTRING("YR "))) {
        // Something went wrong. Perhaps no credentials are accessible.
        return NS_ERROR_FAILURE;
    }

    // It gave us an initial client-to-server request packet. Save that
    // because we'll need it later.
    mInitialMessage = ExtractMessage(line, &mInitialMessageLen);
    if (!mInitialMessage)
        return NS_ERROR_FAILURE;
    return NS_OK;
}
Beispiel #25
0
int main(int argc, char *argv[]) {
  TSocket sock;
  char *servIP;                /* server IP */
  unsigned short servPort;     /* server port */
  char str[100];
  int n;

  if (argc != 3) {
    ExitWithError("Usage: client <remote server IP> <remote server Port>");    
  }

  servIP = argv[1];
  servPort = atoi(argv[2]);

  /* Create a connection */
  sock = ConnectToServer(servIP, servPort);

  for(;;) {
   /* Write msg */
   scanf("%99[^\n]%*c",str);
   n = strlen(str);
   str[n] = '\n';
   if (WriteN(sock, str, ++n) <= 0)
     { ExitWithError("WriteN() failed"); }
   if (strncmp(str, "quit", 4) == 0) break;

   /* Receive the response */
   if (ReadLine(sock, str, 99) < 0)
    { ExitWithError("ReadLine() failed");
   } else printf("%s",str);
   
  }

  close(sock);
  return 0;
}
// Initialize the menu widget from the file
void fill_recent_files_menu (GtkWidget *menu, GtkSignalFunc pfn, gpointer data)
  {
  FILE *pfile = NULL ;
  char *pszFName = NULL ;

  if (NULL == pszRecentFName)
    pszRecentFName = CreateUserFName ("recent") ;

  // If ppszRecentFiles is not NULL, it means we have either already read the recent files,
  // or there are no recent files stored. In the latter case, it's safe to read the file again.
  if (NULL != ppszRecentFiles)
    return ;

  if (NULL == (pfile = fopen (pszRecentFName, "r")))
    return ;

  while (NULL != (pszFName = ReadLine (pfile, '\0', FALSE)))
    {
    ppszRecentFiles = g_realloc (ppszRecentFiles, ++icRecentFiles * sizeof (char *)) ;
    ppszRecentFiles[icRecentFiles - 1] = pszFName ;
    }
  fclose (pfile) ;
  BuildRecentFilesMenu (menu, pfn, data) ;
  }
void * TcpReceiver( void * Ptr )
{
   set_threadname(__func__);
   char TcpString[STRING_SIZE], PacketString[STRING_SIZE];
   unsigned SPktBuf, u;

	(void)Ptr;

   while(true) {
      ReadLine( TcpString );
      if( !strncmp(TcpString, "RESEND", 6)) {
         if ( 2 != sscanf(TcpString, "RESEND %u %s", &SPktBuf, PacketString) ) {
            fprintf(stderr, "ERROR: TcpReceiver - sscanf RESEND\n");
            continue;
         }
         for( u=0; u<SPKT_BUF_PACKET_NUM; u++) {
            if (PacketString[u] == 'y') {
               SPkt.ReSend[SPktBuf][u] = 1;
            } else {
               SPkt.ReSend[SPktBuf][u] = 0;
            }
         }
         SPkt.ReSendStatus[SPktBuf] = 1;
      } else if ( !strncmp(TcpString, "STOP", 4 )) {
         StreamStop=1;
         break;
      } else {
         fprintf(stderr, "ERROR: TcpReader - illegal command\n");
         fflush(stderr);
      }
   }
	sleep(3);
   printf("EXIT\n" );
   fflush(stdout);
   exit(0); // jetzt sollte main() schon bei exit(0) sein
}
Beispiel #28
0
/* Funcion: GetAddresses()
*  -----------------------
*  Toma del archivo f los pares ip-puerto que toma de el.
*  El formato del archivo debe ser un csv, por ejemplo:
*  -----------------------------------------------------
*  127.0.0.1;7777
*  162.168.1.2;1234
*  -----------------------------------------------------
*  Es responsabilidad del usuario abrir el archivo previamente,
*  y cerrarlo luego de la llamada.
*  El valor de retorno sera 1 en caso de que el parseo fue
*  exitoso, y 0 en caso contrario.
*/
int
GetAddresses(FILE * f, address_array_t * adds)
{
	address_t address;
	address_t auxAddress;
	address_t * auxPtr;
	char * aux;

	adds->count = 0;
	adds->addresses = NULL;
	if(f == NULL)
	{
		return 0;	
	}

	while((aux = ReadLine(f))!=NULL)
	{
		if(!GetAddressData(aux, &address))		
		{
			return 0;
		}
		memcpy(&auxAddress, &address, sizeof(address_t));
		auxPtr = (void*)realloc(adds->addresses, (adds->count+ 1)* sizeof(address_t));
		if(auxPtr == NULL)
		{
			return 0;
		}
		adds->addresses = auxPtr;
		memcpy(&(adds->addresses[adds->count]), &address, sizeof(address_t));

		(adds->count)++;
		free(aux);
		
	}
	return 1;
}
Beispiel #29
0
bool CTMDParser::Parse( CTMDParsedData* pData, char* szFileName )
{
	try{
		m_szLineData = new char [255];
		m_pFile = fopen(szFileName, "rb");
		if( NULL == m_pFile ) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);

		// parsing start
		//==========================================================================================================================
		if(!DataVerification(ReadLine(), "*MAP")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		ReadValue(pData->MapInfo.MAP_MAPNAME, ReadLine());
		ReadValue(pData->MapInfo.MAP_MAPTYPE, ReadLine());
		ReadValue(pData->MapInfo.MAP_STATICOBJNUM, ReadLine());
		ReadValue(pData->MapInfo.MAP_DYNAMICOBJNUM, ReadLine());
		ReadValue(pData->MapInfo.MAP_MUSICNAME, ReadLine());
		pData->StaticObject.reserve(pData->MapInfo.MAP_STATICOBJNUM);
		pData->DynamicObject.reserve(pData->MapInfo.MAP_DYNAMICOBJNUM);
		if(!DataVerification(ReadLine(), "}")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		//==========================================================================================================================
		if(!DataVerification(ReadLine(), "*MAPDATA")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		ReadValue(pData->BackInfo.BACK_BACKGNDTEXNAME, ReadLine());
		ReadValue(pData->BackInfo.BACK_BACKGNDRECT, ReadLine());
		if(!DataVerification(ReadLine(), "}")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		//==========================================================================================================================
		if(!DataVerification(ReadLine(), "*OBJECT")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		// Static Object
		//==========================================================================================================================
		if(!DataVerification(ReadLine(), "*STATIC_OBJECT")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		SOBJECT* pSObj;
		if( 0 != pData->MapInfo.MAP_STATICOBJNUM ) pSObj= new SOBJECT [pData->MapInfo.MAP_STATICOBJNUM];
		for(unsigned int i=0; i < pData->MapInfo.MAP_STATICOBJNUM ; i++){
			if(!DataVerification(ReadLine(), "*SOBJECT")) continue;
			ReadValue(pSObj[i].SOBJECT_TEXNAME, ReadLine());
			ReadValue(pSObj[i].SOBJECT_POS, ReadLine());
			ReadValue(pSObj[i].SOBJECT_RECT, ReadLine());
			ReadValue(pSObj[i].SOBJECT_COLOR, ReadLine());
			ReadValue(pSObj[i].SOBJECT_BBOXDATA, ReadLine());
			ReadValue(pSObj[i].SOBJECT_COLTYPE, ReadLine());
			pData->StaticObject.push_back(&pSObj[i]);
			if(!DataVerification(ReadLine(), "}")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		}
		if(!DataVerification(ReadLine(), "}")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		//==========================================================================================================================
		// Dynamic Object
		if(!DataVerification(ReadLine(), "*DYNAMIC_OBJECT")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		DOBJECT* pDObj;
		if( 0 != pData->MapInfo.MAP_DYNAMICOBJNUM ) pDObj = new DOBJECT [pData->MapInfo.MAP_DYNAMICOBJNUM];
		for(unsigned int j=0; j < pData->MapInfo.MAP_DYNAMICOBJNUM ; j++){
			if(!DataVerification(ReadLine(), "*DOBJECT")) continue;
			ReadValue(pDObj[j].DOBJECT_CLASS, ReadLine());
			ReadValue(pDObj[j].DOBJECT_TEXNAME, ReadLine());
			ReadValue(pDObj[j].DOBJECT_POS, ReadLine());
			ReadValue(pDObj[j].DOBJECT_COLOR, ReadLine());
			ReadValue(pDObj[j].DOBJECT_BBOXDATA, ReadLine());
			ReadValue(pDObj[j].DOBJECT_COLTYPE, ReadLine());
			pData->DynamicObject.push_back(&pDObj[j]);
			if(!DataVerification(ReadLine(), "}")) throw("SpotParser.cpp Error line 89");
		}
		if(!DataVerification(ReadLine(), "}")) throw("함수명 : %s, 라인 : %d \n", __FUNCTION__, __LINE__);
		//==========================================================================================================================
		// parsing end

		fclose(m_pFile);
		SAFE_DELETE(m_szLineData);

	}catch(char* errmsg){
		::MessageBox(NULL, errmsg, "Error", MB_OK);
		fclose(m_pFile);
		SAFE_DELETE(m_szLineData);
		return false;
	}

	return true;
}
int S57ClassRegistrar::LoadInfo( const char * pszDirectory,
                                 const char * pszProfile,
                                 int bReportErr )

{
    if( pszDirectory == NULL )
        pszDirectory = CPLGetConfigOption("S57_CSV",NULL);

/* ==================================================================== */
/*      Read the s57objectclasses file.                                 */
/* ==================================================================== */
    if( pszProfile == NULL )
        pszProfile = CPLGetConfigOption( "S57_PROFILE", "" );

    char szTargetFile[1024];  // TODO: Get this off of the stack.
    if( EQUAL(pszProfile, "Additional_Military_Layers") )
    {
       snprintf( szTargetFile, sizeof(szTargetFile), "s57objectclasses_%s.csv", "aml" );
    }
    else if ( EQUAL(pszProfile, "Inland_Waterways") )
    {
       snprintf( szTargetFile, sizeof(szTargetFile), "s57objectclasses_%s.csv", "iw" );
    }
    else if( strlen(pszProfile) > 0 )
    {
       snprintf( szTargetFile, sizeof(szTargetFile), "s57objectclasses_%s.csv", pszProfile );
    }
    else
    {
       strcpy( szTargetFile, "s57objectclasses.csv" );
    }

    VSILFILE *fp = NULL;
    if( !FindFile( szTargetFile, pszDirectory, bReportErr, &fp ) )
        return FALSE;

/* -------------------------------------------------------------------- */
/*      Skip the line defining the column titles.                       */
/* -------------------------------------------------------------------- */
    const char * pszLine = ReadLine( fp );

    if( !EQUAL(pszLine,
               "\"Code\",\"ObjectClass\",\"Acronym\",\"Attribute_A\","
               "\"Attribute_B\",\"Attribute_C\",\"Class\",\"Primitives\"" ) )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "s57objectclasses columns don't match expected format!\n" );
        if( fp != NULL )
            VSIFCloseL( fp );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Read and form string list.                                      */
/* -------------------------------------------------------------------- */
    apszClassesInfo.Clear();
    while( (pszLine = ReadLine(fp)) != NULL )
    {
        apszClassesInfo.AddString(pszLine);
    }

/* -------------------------------------------------------------------- */
/*      Cleanup, and establish state.                                   */
/* -------------------------------------------------------------------- */
    if( fp != NULL )
        VSIFCloseL( fp );

    nClasses = apszClassesInfo.size();
    if( nClasses == 0 )
        return FALSE;

/* ==================================================================== */
/*      Read the attributes list.                                       */
/* ==================================================================== */

    if( EQUAL(pszProfile, "Additional_Military_Layers") )
    {
      snprintf( szTargetFile, sizeof(szTargetFile), "s57attributes_%s.csv", "aml" );
    }
    else if ( EQUAL(pszProfile, "Inland_Waterways") )
    {
       snprintf( szTargetFile, sizeof(szTargetFile),"s57attributes_%s.csv", "iw" );
    }
    else if( strlen(pszProfile) > 0 )
    {
       snprintf( szTargetFile, sizeof(szTargetFile), "s57attributes_%s.csv", pszProfile );
    }
    else
    {
       strcpy( szTargetFile, "s57attributes.csv" );
    }

    if( !FindFile( szTargetFile, pszDirectory, bReportErr, &fp ) )
        return FALSE;

/* -------------------------------------------------------------------- */
/*      Skip the line defining the column titles.                       */
/* -------------------------------------------------------------------- */
    pszLine = ReadLine( fp );

    if( !EQUAL(pszLine,
          "\"Code\",\"Attribute\",\"Acronym\",\"Attributetype\",\"Class\"") )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "s57attributes columns don't match expected format!\n" );
        if( fp != NULL )
            VSIFCloseL( fp );
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Read and form string list.                                      */
/* -------------------------------------------------------------------- */
    while( (pszLine = ReadLine(fp)) != NULL )
    {
        char    **papszTokens = CSLTokenizeStringComplex( pszLine, ",",
                                                          TRUE, TRUE );

        if( CSLCount(papszTokens) < 5 )
        {
            CPLAssert( FALSE );
            continue;
        }

        int iAttr = atoi(papszTokens[0]);
        if( iAttr >= (int) aoAttrInfos.size() )
            aoAttrInfos.resize(iAttr+1);

        if( iAttr < 0 || aoAttrInfos[iAttr] != NULL )
        {
            CPLDebug( "S57",
                      "Duplicate/corrupt definition for attribute %d:%s",
                      iAttr, papszTokens[2] );
            CSLDestroy( papszTokens );
            continue;
        }

        aoAttrInfos[iAttr] = new S57AttrInfo();
        aoAttrInfos[iAttr]->osName = papszTokens[1];
        aoAttrInfos[iAttr]->osAcronym = papszTokens[2];
        aoAttrInfos[iAttr]->chType = papszTokens[3][0];
        aoAttrInfos[iAttr]->chClass = papszTokens[4][0];
        anAttrIndex.push_back(iAttr);
        CSLDestroy( papszTokens );
    }

    if( fp != NULL )
        VSIFCloseL( fp );

    nAttrCount = static_cast<int>(anAttrIndex.size());

/* -------------------------------------------------------------------- */
/*      Sort index by acronym.                                          */
/* -------------------------------------------------------------------- */
    bool bModified = false;
    do
    {
        bModified = false;
        for( int iAttr = 0; iAttr < nAttrCount-1; iAttr++ )
        {
            if( strcmp(aoAttrInfos[anAttrIndex[iAttr]]->osAcronym,
                       aoAttrInfos[anAttrIndex[iAttr+1]]->osAcronym) > 0 )
            {
                int nTemp = anAttrIndex[iAttr];
                anAttrIndex[iAttr] = anAttrIndex[iAttr+1];
                anAttrIndex[iAttr+1] = nTemp;
                bModified = true;
            }
        }
    } while( bModified );

    return TRUE;
}