示例#1
0
int checkNumber(FILE *fp, int tokenStart){
    if(isdigit(tokenStart)){
        int i;
        char lexeme[20] = {'\0'};
        lexeme[0] = tokenStart;

        //Loop through the next 1-4 digits to build lexeme
        for(i = 1; i < 5; i++){
            char workingDigit = fpeek(fp);
            if(isdigit(workingDigit)){
                lexeme[i] = fgetc(fp);
            }
            else if(isalpha(workingDigit) || workingDigit == '_'){
                return 1; //Error, Variable does not start with letter
            }
            else{
                break;
            }
        }

        if(i == 5 && isdigit(fpeek(fp))){
            return 2; //Error, number is too long
        }

        createToken(lexeme, numbersym);

        return 0;

    }
}
示例#2
0
int checkVariable(FILE *fp, int tokenStart){
    if(isalpha(tokenStart) || tokenStart == '_'){
        int i;
        char lexeme[20] = {'\0'};
        lexeme[0] = tokenStart;

        //Loop through the next 1-10 characters to build lexeme
        for(i = 1; i < 11; i++){
            char workingChar = fpeek(fp);
            if(isalnum(workingChar) || workingChar == '_'){
                lexeme[i] = fgetc(fp);
            }
            else{
                break;
            }
        }

        //If there's a 12th alphanumeric character after the 11th, name is too long
        if(i == 11 && (isalnum(fpeek(fp)) || fpeek(fp) == '_')){
            return 3; //Error, name is too long
        }

        createToken(lexeme, identsym);

        return 0;

    }
    else{
        return -1;
    }
}
示例#3
0
文件: player.cpp 项目: brthiess/morat
//reads the format from gen_hgf.
void Player::load_hgf(Board board, Node * node, FILE * fd){
	char c, buf[101];

	eat_whitespace(fd);

	assert(fscanf(fd, "(;%c[%100[^]]]", &c, buf) > 0);

	assert(board.toplay() == (c == 'W' ? 1 : 2));
	node->move = Move(buf);
	board.move(node->move);

	assert(fscanf(fd, "C[%100[^]]]", buf) > 0);

	vecstr entry, parts = explode(string(buf), ", ");
	assert(parts[0] == "mcts");

	entry = explode(parts[1], ":");
	assert(entry[0] == "sims");
	uword sims = from_str<uword>(entry[1]);

	entry = explode(parts[2], ":");
	assert(entry[0] == "avg");
	double avg = from_str<double>(entry[1]);

	uword wins = sims*avg;
	node->exp.addwins(wins);
	node->exp.addlosses(sims - wins);

	entry = explode(parts[3], ":");
	assert(entry[0] == "outcome");
	node->outcome = from_str<int>(entry[1]);

	entry = explode(parts[4], ":");
	assert(entry[0] == "best");
	node->bestmove = Move(entry[1]);


	eat_whitespace(fd);

	if(fpeek(fd) != ')'){
		create_children_simple(board, node);

		while(fpeek(fd) != ')'){
			Node child;
			load_hgf(board, & child, fd);

			Node * i = find_child(node, child.move);
			*i = child;          //copy the child experience to the tree
			i->swap_tree(child); //move the child subtree to the tree

			assert(child.children.empty());

			eat_whitespace(fd);
		}
	}

	eat_char(fd, ')');

	return;
}
示例#4
0
void read_in_number(token * t, fileStruct *files) {
    strcpy(t->type, "INTLIT");
    t->number = INTLIT;
    int index = strlen(t->actual);
    while (isdigit(fpeek(files->input))) {
        t->actual[index] = fgetc(files->input);
        index++;
    }
    // if we encounter a period, it's a real
    if (fpeek(files->input) == '.') {
        strcpy(t->type, "REALLIT");
        t->number = REALLIT;
        t->actual[index++] = fgetc(files->input);
        while (isdigit(fpeek(files->input))) {
            t->actual[index++] = fgetc(files->input);
        }
    }
}
示例#5
0
int ReadFileLine(FILE *pInFile, mod_prec *iAppArray){

	char c= fpeek(pInFile);
	if (c==EOF)
		return 0;
	
	char *strNumber;
	int bufSize = cellCount*20;	//more than enough but will do for nao
	char* buffer = (char*) malloc(bufSize*sizeof(char));

	int floats_ignored = 0;
	int floats_needed = cellCount;
	int useful_element_found = 0;
	//int i will stand for elements already processed, hence it starts at 0 even after the first strtok
	int i = 0;
	
	//Get one line
	if(fgets(buffer, bufSize, pInFile)){
		//Convert the ASCII string of one element to a double precision floating point value
		strNumber = strtok(buffer," ");
		i = 0;

		while ((strNumber != NULL) && (i<IO_NETWORK_SIZE)){
			if (i>=floats_ignored)
				useful_element_found = 1;

			if (i>=floats_ignored+floats_needed)
				useful_element_found = 0;

			if (useful_element_found)
				iAppArray[i-floats_ignored] = atof(strNumber);	//atof() should change if using integers or fixed point
			strNumber = strtok(NULL, " ");
			i++; 
		}
	
		if(i<IO_NETWORK_SIZE){
			//BUG: if only one element is missing but the line ends in a space, the error is not detected
			printf("Error: Input line doesn't have enough elements, only %d\n", i);
			exit(EXIT_FAILURE);
		}
		free(buffer);

		return 1;//success
	}else{
		if(!feof(pInFile)){
			printf("Error: Reading from input file didn't finish successfully\n");
			exit(EXIT_FAILURE);
		}
		free(buffer);
		return 0;//end of file
	}
}
示例#6
0
int cleanFile(FILE *input, FILE *cleanInput){
    printf("Cleaning input...");

    while(fpeek(input) != EOF){
        char nextChar = fgetc(input); //Grab the next char from input

        if(nextChar == '/'){ //Possibly a comment
            if(fpeek(input) == '*'){ //Start comment block
                fgetc(input); // "/*"
                while(fpeek(input) != '*') // "/*..."
                    fgetc(input);

                fgetc(input); // "/*...*"
                fgetc(input); // "/*...*/"

                continue; //Comment block over
            }
        }

        fputc(nextChar, cleanInput); //Copy the char over
    }

    printf("COMPLETE\n");
}
示例#7
0
文件: ppm.cpp 项目: eriser/dataflow
    void try_comment(FILE * f)
    {
        char linebuf[1024];
        char ppp;

        while (true) {
            while (ppp = fpeek(f), ppp == '\n' || ppp == '\r')
                fgetc(f);

            if (ppp == '#')
                fgets(linebuf, 1023, f);
            else
                break;
        }
    }
int ReadFileLine(FILE *pFile, float *matrix, int size){

	char c= fpeek(pFile);
	if (c==EOF)
		return 0;
	char *strNumber;
	int bufSize = size*30;
	char* buffer = (char*) calloc(bufSize, sizeof(char));
	int i = 0;

	//Get one line
	if(fgets(buffer, bufSize, pFile)){
	//Convert the ASCII string of one element to a floating point value
		strNumber = strtok(buffer," ");
		i = 0;

		while ((strNumber != NULL) && (i<size)){

			//store number
                        matrix[i] = atof(strNumber);
			//get next
			strNumber = strtok(NULL, " ");
			i++;
		}

		if(i<size){
		//BUG: if only one element is missing but the line ends in a space, the error is not detected
			printf("Error: Input line doesn't have enough elements, only %d\n", i);
			exit(EXIT_FAILURE);
		}

		free(buffer);
		return 1;//success
	}else{

		if(!feof(pFile)){
			printf("Error: Reading from input file didn't finish successfully\n");
			exit(EXIT_FAILURE);
		}

		free(buffer);
		return 0;//end of file
	}
}
示例#9
0
static bool is_binary_file(QString fn)
{
  if (!QFile::exists(fn)) {
    fn = klfSearchPath(fn);
  }
  QFile fpeek(fn);
  if (!fpeek.open(QIODevice::ReadOnly)) {
    klfDbg("fn="<<fn<<", Can't peek into file "<<fn<<"!") ;
  } else {
    QByteArray line;
    int n = 0, j;
    while (n++ < 3 && (line = fpeek.readLine()).size()) {
      for (j = 0; j < line.size(); ++j) {
        if ((int)line[j] >= 127 || (int)line[j] <= 0) {
          return true;
        }
      }
    }
    return false;
  }
  return false;
}
示例#10
0
int checkSymbols(FILE *fp, int tokenStart){

    switch(tokenStart){
        case '+': //Plus
            createToken("+", plussym);
            return(0);

        case '-': //Minus
            createToken("-", minussym);
            return(0);

        case '*': //Mult
            createToken("*", multsym);
            return(0);

        case '/': //Slash
            createToken("/", slashsym);
            return(0);

        case '(': //LParen
            createToken("(", lparentsym);
            return(0);

        case ')': //RParen
            createToken(")", rparentsym);
            return(0);

        case '=': //Equals
            createToken("=", eqsym);
            return(0);

        case ',': //Comma
            createToken(",", commasym);
            return(0);

        case '.': //Period
            createToken(".", periodsym);
            return(0);

        case '<': //Less, leq, neq
            if(fpeek(fp) == '='){
                fgetc(fp);
                createToken("<=", leqsym);
            }
            else if(fpeek(fp) == '>'){
                fgetc(fp);
                createToken("<>", neqsym);
            }
            else{
                createToken("<", lessym);
            }
            return(0);

        case '>': //gtr & geq
            if(fpeek(fp) == '='){
                fgetc(fp);
                createToken(">=", geqsym);
            }
            else
                createToken(">", gtrsym);
            return(0);

        case ';': //Semicolon
            createToken(";", semicolonsym);
            return(0);

        case ':': //Becomes
            if(fpeek(fp) == '='){
                createToken(":=", becomessym);
                fgetc(fp);
                return(0);
            }
            break;
        default:
            if(!(isalnum(tokenStart) || tokenStart == '_'))
                return 4; //Not a valid symbol


        return -1;

    }

}
示例#11
0
int
main (int argc, char **argv)
{
    char            *inFname = "stdin"; /* Name of input source */
    char            *outFname = "stdout";  /* Name of output destination */
    char            *Label;             /* Names of input coordinates */
    char            Tail[4096] = {0};   /* Rest of input line beyond coords */
    extern char     *bu_optarg;         /* argument from bu_getopt(3C) */
    FILE            *inPtr = stdin;     /* Pointer to input */
    FILE            *outPtr = stdout;   /* Pointer to output */
    double          Azim = 0.0;         /* Azimuth angle (in degrees) */
    double          Elev = 0.0;         /* Elevation angle (in degrees) */
    double          CelSiz = 1.0;       /* Size of cells (dimensionless) */
    double          Cazim;              /* Cosine of the azimuth angle */
    double          Celev;              /* Cosine of the elevation angle */
    double          Sazim;              /* Sine of the azimuth angle */
    double          Selev;              /* Sine of the elevation angle */
    double          U1;                 /* Input coords of current point */
    double          V1;                 /*   "      "    "    "      "   */
    double          W1;                 /*   "      "    "    "      "   */
    double          U2;			/* Output coords of current point */
    double          V2;                 /*   "      "    "    "      "   */
    double          W2;                 /*   "      "    "    "      "   */
    double          UU;                 /* Weight of U1 in computing U2 */
    double          UV;                 /*    "    " U1  "     "     V2 */
    double          UW;                 /*    "    " U1  "     "     W2 */
    double          VU;                 /* Weight of V1 in computing U2 */
    double          VV;                 /*    "    " V1  "     "     V2 */
    double          VW;                 /*    "    " V1  "     "     W2 */
    double          WU;                 /* Weight of W1 in computing U2 */
    double          WV;                 /*    "    " W1  "     "     V2 */
    double          WW;                 /*    "    " W1  "     "     W2 */
    int             Invert = 0;		/* Undo az-el rotation? */
    int             PlanarProj = 0;	/* Project points onto plane? */
    int             Round = 0;		/* Round the output coords? */
    int             LineNm = 0;         /* How far through input? */
    int             Ch;                 /* Input character */
    int             i;                  /* Dummy variable for loop indexing */
    extern int      bu_optind;             /* index from bu_getopt(3C) */

    /* Handle command-line options */
    while ((Ch = bu_getopt(argc, argv, OPT_STRING)) != EOF)
	switch (Ch)
	{
	    case 'a':
		if (sscanf(bu_optarg, "%lf", &Azim) != 1)
		{
		    (void) fprintf(stderr,
				   "Bad azimuth specification: '%s'\n", bu_optarg);
		    PrintUsage();
		}
		break;
	    case 'c':
		if (sscanf(bu_optarg, "%lf", &CelSiz) != 1)
		{
		    (void) fprintf(stderr,
				   "Bad cell-size specification: '%s'\n", bu_optarg);
		    PrintUsage();
		}
		break;
	    case 'e':
		if (sscanf(bu_optarg, "%lf", &Elev) != 1)
		{
		    (void) fprintf(stderr,
				   "Bad elevation specification: '%s'\n", bu_optarg);
		    PrintUsage();
		}
		break;
	    case 'i':
		Invert = 1;
		break;
	    case 'p':
		PlanarProj = 1;
		break;
	    case 'r':
		Round = 1;
		break;
	    default:
		fprintf(stderr, "Bad option '-%c'\n", Ch);
	    case '?':
		PrintUsage();
	}

    if (PlanarProj && Invert)
    {
	fputs("Incompatible options: -i and -p\n", stderr);
	PrintUsage();
    }

    /* Determine source and destination */
    if (argc - bu_optind > 0)
    {
	inFname = argv[bu_optind];
	if ((inPtr = fopen(inFname, "r")) == NULL)
	{
	    bu_exit(1, "azel:  Cannot open file '%s'\n", inFname);
	}
	if (argc - bu_optind > 1)
	{
	    outFname = argv[bu_optind + 1];
	    if ((outPtr = fopen(outFname, "w")) == NULL)
	    {
		bu_exit(1, "azel:  Cannot create file '%s'\n", outFname);
	    }
	}
	if (argc - bu_optind > 2)
	{
	    PrintUsage();
	}
    }

    /* Compute transformation coefficients */
    Cazim = cos(Azim * DEG2RAD);
    Celev = cos(Elev * DEG2RAD);
    Sazim = sin(Azim * DEG2RAD);
    Selev = sin(Elev * DEG2RAD);
    if (Invert)
    {
	UU = Celev * Cazim;
	VU = -Sazim;
	WU = -(Selev * Cazim);
	UV = Celev * Sazim;
	VV = Cazim;
	WV = -(Selev * Sazim);
	UW = Selev;
	VW = 0.0;
	WW = Celev;
    }
    else
    {
	UU = Celev * Cazim;
	VU = Celev * Sazim;
	WU = Selev;
	UV = -Sazim;
	VV = Cazim;
	WV = 0.0;
	UW = -(Selev * Cazim);
	VW = -(Selev * Sazim);
	WW = Celev;
    }

/* * * * * Filter Data * * * * */
    Label = Invert ? "DHV" : "XYZ";

    while ((Ch = fpeek(inPtr)) != EOF)
    {
/* Read U1, V1, and W1 of next point in input frame of reference */
	GetCoord(inPtr, &U1, *Label, LineNm + 1, inFname);
	GetCoord(inPtr, &V1, *(Label + 1), LineNm + 1, inFname);
	GetCoord(inPtr, &W1, *(Label + 2), LineNm + 1, inFname);

/* Compute U2, V2, and W2 for this point */
	U2 = (U1 * UU + V1 * VU + W1 * WU) / CelSiz;
	V2 = (U1 * UV + V1 * VV + W1 * WV) / CelSiz;
	W2 = (U1 * UW + V1 * VW + W1 * WW) / CelSiz;

	if (Round)
	{
	    U2 = floor(U2 + .5);
	    V2 = floor(V2 + .5);
	    W2 = floor(W2 + .5);
	}

/* Read in the rest of the line for subsequent dumping out */
	for (i = 0; (Ch = fgetc(inPtr)) != '\n'; i++)
	    if (Ch == EOF)
	    {
		Tail[i] = '\n';
		break;
	    }
	    else
		Tail[i] = Ch;
	Tail[i] = '\0';

/* Write out the filtered version of this line */
	if (! PlanarProj)
	    fprintf(outPtr, "%g\t", U2);
	fprintf(outPtr, "%g\t%g\t%s\n", V2, W2, Tail);
	LineNm++;
    }
    bu_exit (0, NULL);
}
示例#12
0
int checkReservedWords(FILE *fp, int tokenStart){

    fpos_t resetpos;
    fgetpos(fp, &resetpos);

    if(tokenStart == 'b'){
        if(fgetc(fp) == 'e'){
            if(fgetc(fp) == 'g'){
                if(fgetc(fp) == 'i'){
                    if(fgetc(fp) == 'n'){
                        if(!isalnum(fpeek(fp))){
                            createToken("begin", beginsym);
                            return 0;
                        }
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'c'){
        if(fgetc(fp) == 'a'){
            if(fgetc(fp) == 'l'){
                if(fgetc(fp) == 'l'){
                    if(!isalnum(fpeek(fp))){
                        createToken("call", callsym);
                        return 0;
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'c'){
        if(fgetc(fp) == 'o'){
            if(fgetc(fp) == 'n'){
                if(fgetc(fp) == 's'){
                    if(fgetc(fp) == 't'){
                        if(!isalnum(fpeek(fp))){
                            createToken("const", constsym);
                            return 0;
                        }
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'd'){
        if(fgetc(fp) == 'o'){
            if(!isalnum(fpeek(fp))){
                createToken("do", dosym);
                return 0;
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'e'){
        if(fgetc(fp) == 'l'){
            if(fgetc(fp) == 's'){
                if(fgetc(fp) == 'e'){
                    if(!isalnum(fpeek(fp))){
                        createToken("else", elsesym);
                        return 0;
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'e'){
        if(fgetc(fp) == 'n'){
            if(fgetc(fp) == 'd'){
                if(!isalnum(fpeek(fp))){
                    createToken("end", endsym);
                    return 0;
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'i'){
        if(fgetc(fp) == 'f'){
            if(!isalnum(fpeek(fp))){
                createToken("if", ifsym);
                return 0;
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'o'){
        if(fgetc(fp) == 'd'){
            if(fgetc(fp) == 'd'){
                if(!isalnum(fpeek(fp))){
                    createToken("odd", oddsym);
                    return 0;
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'p'){
        if(fgetc(fp) == 'r'){
            if(fgetc(fp) == 'o'){
                if(fgetc(fp) == 'c'){
                    if(fgetc(fp) == 'e'){
                        if(fgetc(fp) == 'd'){
                            if(fgetc(fp) == 'u'){
                                if(fgetc(fp) == 'r'){
                                    if(fgetc(fp) == 'e'){
                                        if(!isalnum(fpeek(fp))){
                                            createToken("procedure", procsym);
                                            return 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'r'){
        if(fgetc(fp) == 'e'){
            if(fgetc(fp) == 'a'){
                if(fgetc(fp) == 'd'){
                    if(!isalnum(fpeek(fp))){
                        createToken("read", readsym);
                        return 0;
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 't'){
        if(fgetc(fp) == 'h'){
            if(fgetc(fp) == 'e'){
                if(fgetc(fp) == 'n'){
                    if(!isalnum(fpeek(fp))){
                        createToken("then", thensym);
                        return 0;
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);


    if(tokenStart == 'v'){
        if(fgetc(fp) == 'a'){
            if(fgetc(fp) == 'r'){
                if(!isalnum(fpeek(fp))){
                    createToken("var", varsym);
                    return 0;
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'w'){
        if(fgetc(fp) == 'h'){
            if(fgetc(fp) == 'i'){
                if(fgetc(fp) == 'l'){
                    if(fgetc(fp) == 'e'){
                        if(!isalnum(fpeek(fp))){
                            createToken("while", whilesym);
                            return 0;
                        }
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    if(tokenStart == 'w'){
        if(fgetc(fp) == 'r'){
            if(fgetc(fp) == 'i'){
                if(fgetc(fp) == 't'){
                    if(fgetc(fp) == 'e'){
                        if(!isalnum(fpeek(fp))){
                            createToken("write", writesym);
                            return 0;
                        }
                    }
                }
            }
        }
    }

    fsetpos(fp, &resetpos);

    return -1;

}
示例#13
0
文件: svg.c 项目: ppiecuch/vsprite
void skip_whitespace() {
    while( !feof(input) && isspace(fpeek(input)) )
          fgetc(input);
}
示例#14
0
token process_symbol(char c, fileStruct *files)
{
    token out;
    wipeout(&out);
    ungetc(c, files->input); // woops
    if (fpeek(files->input) == '<') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "LTSIGN");
        out.number = LTSIGN;
        if (fpeek(files->input) == '=') {
            out.actual[1] = fgetc(files->input);
            strcpy(out.type, "LTESIGN");
            out.number = LTESIGN;
        }
        else if (fpeek(files->input) == '>') {
            out.actual[1] = fgetc(files->input);
            strcpy(out.type, "NOTEQSIGN");
            out.number = NOTEQSIGN;
        }
    } 
    else if (fpeek(files->input) == '>') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "GTSIGN");
        out.number = GTSIGN;
        if (fpeek(files->input) == '=') {
            out.actual[1] = fgetc(files->input);
            strcpy(out.type, "GTESIGN");
            out.number = GTESIGN;
        }
    } 
    else if (fpeek(files->input) == ';') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "SEMICOLON");
        out.number = SEMICOLON;

    } 
    else if (fpeek(files->input) == '=') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "ASSIGN");
        out.number = ASSIGN;
        if (fpeek(files->input) == '=') {
            out.actual[1] = fgetc(files->input);
            strcpy(out.type, "EQUIVSIGN");
            out.number = EQUIVSIGN;
        }
    } 
    else if (fpeek(files->input) == ',') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "COMMA");
        out.number = COMMA;
    } 
    else if (fpeek(files->input) == '*') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "MULTOP");
        out.number = MULTOP;
    }
    else if (fpeek(files->input) == '/') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "DIVOP");
        out.number = DIVOP;
    }
    else if (fpeek(files->input) == '-') {
        out.actual[0] = fgetc(files->input);
        // interpret "- " as minus operator
        if (fpeek(files->input) == ' ') { 
            strcpy(out.type, "MINUSOP");
            out.number = MINUSOP;
        }
        // interpret "-letter" as negation of identifier
        else if (isalpha(fpeek(files->input))) {
            strcpy(out.type, "NEGATION");
            out.number = NEGATION;
        }
        // interpret "-\d+" as a negative number
        else if (isdigit(fpeek(files->input))) {
            read_in_number(&out, files);
        }
        else if (fpeek(files->input) == '-') {
            // this is a comment... 
            fgetc(files->input);
            while (fgetc(files->input) != '\n') {
                // throw it all in the bit bucket
            }
            out.actual[0] = '\0';
            strcpy(out.type, "Comment skipped");
            out.number = -1;
        }
        else {
            // error 
            out.actual[0] = fgetc(files->input);
            strcpy(out.type, "ERROR");
            out.number = ERROR;
        }
    }
    else if (fpeek(files->input) == '+') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "PLUSOP");
        out.number = PLUSOP;
    }
    else if (fpeek(files->input) == '^') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "EXPOP");
        out.number = EXPOP;
    }
    else if (fpeek(files->input) == '"') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "STRINGLIT");
        out.number = STRINGLIT;
        // from here, we need to accept any ascii char except double quote unless preceded by a backslash
        int index = 1;
        while ( (!feof(files->input)) && fpeek(files->input) != '"' ) {
            if (fpeek(files->input) == '\\') {
                // escape sequences
                out.actual[index++] = fgetc(files->input);
            }
            out.actual[index++] = fgetc(files->input);
        }
        if (!feof(files->input)) {
            out.actual[index] = fgetc(files->input); // wipe out the last "
        }
    }
    else if (fpeek(files->input) == '(') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "LPAREN");
        out.number = LPAREN;
    }
    else if (fpeek(files->input) == ')') {
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "RPAREN");
        out.number = RPAREN;
    }
    else {
        // error
        out.actual[0] = fgetc(files->input);
        strcpy(out.type, "ERROR");
        out.number = ERROR;
    }
	strcat(linebuff,out.actual);
    return out;
}
示例#15
0
celix_status_t manifest_read(manifest_pt manifest, char *filename) {
    celix_status_t status = CELIX_SUCCESS;

	FILE *file = fopen ( filename, "r" );
	if (file != NULL) {
		char lbuf[512];
		char name[512];
		bool skipEmptyLines = true;
		char lastline[512];
		name[0] = '\0';

		manifest_readAttributes(manifest, manifest->mainAttributes, file);
		
		while (status==CELIX_SUCCESS && fgets(lbuf, sizeof(lbuf), file) != NULL) {
			properties_pt attributes;
			int len = strlen(lbuf);

			if (lbuf[--len] != '\n') {
				status = CELIX_FILE_IO_EXCEPTION;
				framework_logIfError(logger, status, NULL, "Manifest '%s' line too long", filename);
				return status;
			}
			if (len > 0 && lbuf[len - 1] == '\r') {
				--len;
			}
			if (len == 0 && skipEmptyLines) {
				continue;
			}
			skipEmptyLines = false;

			if (strlen(name) == 0) {
				
				if ((tolower(lbuf[0]) == 'n') && (tolower(lbuf[1]) == 'a') &&
					(tolower(lbuf[2]) == 'm') && (tolower(lbuf[3]) == 'e') &&
					(lbuf[4] == ':') && (lbuf[5] == ' ')) {
					name[0] = '\0';
					strncpy(name, lbuf+6, len - 6);
					name[len - 6] = '\0';
				} else {
					status = CELIX_FILE_IO_EXCEPTION;
					framework_logIfError(logger, status, NULL, "Manifest '%s' invalid format", filename);
					return status;
				}

				if (fpeek(file) == ' ') {
					int newlen = len - 6;
					lastline[0] = '\0';
					strncpy(lastline, lbuf+6, len - 6);
					lastline[newlen] = '\0';
					continue;
				}
			} else {
				int newlen = strlen(lastline) + len;
				char buf[512];
				buf[0] = '\0';
				strcpy(buf, lastline);
				strncat(buf, lbuf+1, len - 1);
				buf[newlen] = '\0';

				if (fpeek(file) == ' ') {
//					lastline = realloc(lastline, strlen(buf) + 1);
					lastline[0] = '\0';
					strcpy(lastline, buf);
					continue;
				}
				name[0] = '\0';
				strcpy(name, buf);
				name[strlen(buf)] = '\0';
			}

			attributes = hashMap_get(manifest->attributes, name);
			if (attributes == NULL) {
				attributes = properties_create();
				hashMap_put(manifest->attributes, strdup(name), attributes);
			}
			manifest_readAttributes(manifest, attributes, file);

			name[0] = '\0';
			skipEmptyLines = true;
		}
		fclose(file);
	} else {
		status = CELIX_FILE_IO_EXCEPTION;
	}

	framework_logIfError(logger, status, NULL, "Cannot read manifest");

	return status;
}
示例#16
0
celix_status_t manifest_readAttributes(manifest_pt manifest, properties_pt properties, FILE *file) {
	char name[512];
	char value[512];
	char lastLine[512];
	char lbuf[512];


	while (fgets(lbuf, sizeof(lbuf), file ) != NULL ) {
		bool lineContinued = false;
		int len = strlen(lbuf);

		if (lbuf[--len] != '\n') {
			printf("MANIFEST: Line too long\n");
			return CELIX_FILE_IO_EXCEPTION;
		}
		if (len > 0 && lbuf[len - 1] == '\r') {
			--len;
		}
		if (len == 0) {
			break;
		}
		
		if (lbuf[0] == ' ') {
			char buf[512];
			buf[0] = '\0';

			// Line continued
			lineContinued = true;
			strcat(buf, lastLine);
			strncat(buf, lbuf+1, len - 1);

			if (fpeek(file) == ' ') {
//				lastLine = realloc(lastLine, strlen(buf) + 1);
				lastLine[0] = '\0';
				strcpy(lastLine, buf);
				continue;
			}
			value[0] = '\0';
			strcpy(value, buf);
		} else {
	        int i = 0;
			while (lbuf[i++] != ':') {
				if (i >= len) {
					printf("MANIFEST: Invalid header\n");
					return CELIX_FILE_IO_EXCEPTION;
				}
			}
			if (lbuf[i++] != ' ') {
				printf("MANIFEST: Invalid header\n");
				return CELIX_FILE_IO_EXCEPTION;
			}
			name[0] = '\0';
			strncpy(name, lbuf, i - 2);
			name[i - 2] = '\0';
			if (fpeek(file) == ' ') {
				int newlen = len - i;
				lastLine[0] = '\0';
				strncpy(lastLine, lbuf+i, len -i);
				lastLine[newlen] = '\0';
				continue;
			}
			value[0] = '\0';
			strncpy(value, lbuf+i, len - i);
			value[len - i] = '\0';
		}

		if ((properties_set(properties, name, value) != NULL) && (!lineContinued)) {
			printf("Duplicate entry: %s", name);
		}
	}

	return CELIX_SUCCESS;
}
示例#17
0
int get_next_xml_token(FILE* F, a_string_t *tok, int *in_element)
{
  int c,marker;
  
  while (isspace(c = fpeek(F))) xfgetc(F);
  
  a_strcpy(tok,"");

  c = xfgetc(F);

  if (*in_element>=TOK_BEGIN)
  {
    if (c=='\'' || c=='"')
    {
      marker = c;
      *in_element =  TOK_STRING;
      for (;;)
      {
	c = xfgetc(F);
	if (c==marker) return XML_OK;
	if (c==EOF) {
	  log_printf(LOG_ERROR,"unterminated quoted value");
	  return XML_ERROR;
	}
	a_strpushback(tok,c);
      }
    }

    if (c=='=')
    {
      *in_element = TOK_EQUAL;
      a_strcpy(tok,"=");
      return XML_OK;
    }

    if (c=='>')
    {
      a_strcpy(tok,">");
      *in_element=TOK_GTE;
      return XML_OK;
    }

    if (c=='/')
    {
      c = xfgetc(F);
      if (c!='>') {
	log_printf(LOG_ERROR,"Expected '>'");
	return XML_ERROR;
      }
      a_strcpy(tok,"/>");
      *in_element=TOK_SLASH_GTE;
      return XML_OK;
    }

    *in_element=TOK_ATTRIBUTE;
    if (!isvalid(c)) return XML_ERROR;
    a_strpushback(tok,c);

    for (;;)
    {
      c = fpeek(F);
      if (c==EOF) {
	log_printf(LOG_ERROR,"Unterminated attribute '%s...'",a_strval(tok));
	return XML_ERROR;
      }
      if (!isvalid(c)) return XML_OK;
      a_strpushback(tok,xfgetc(F));
    }
    return XML_OK;
  }
  else
  {
    if (c=='<')
    {
      a_strpushback(tok,c);
      c = fgetc(F);

      if (c=='?' || c=='!' || c=='/')
      {
	if (c=='/')
	  *in_element=TOK_END;
	else
	  *in_element=TOK_INSTRUCTION;

	a_strpushback(tok,c);
	for (;;)
	{
	  c = xfgetc(F);
	  if (c==EOF) {
	    log_printf(LOG_ERROR,"Unterminated '%s...'",a_strval(tok));
	    return XML_ERROR;
	  }
	  if (c=='>') {
	    a_strpushback(tok,'>');
	    return XML_OK;
	  }
	}
      }

      *in_element=TOK_BEGIN;
      if (!isvalid(c)) return XML_ERROR;
      a_strpushback(tok,c);

      for (;;)
      {
	c = fpeek(F);
	if (c==EOF) {
	  log_printf(LOG_ERROR,"Unterminated element '%s...'",a_strval(tok));
	  return XML_ERROR;
	}
	if (!isvalid(c)) return XML_OK;
	a_strpushback(tok,xfgetc(F));
      }
    }
    else /* if c=='<' */
    {
      *in_element=TOK_TEXT;

      a_strpushback(tok,c);
      for (;;)
      {
	c = fpeek(F);
	if (c==EOF) {
	  log_printf(LOG_ERROR,"Unterminated data '%s...'",a_strval(tok));
	  return XML_ERROR;
	}
	if (c=='<') return XML_OK;
	a_strpushback(tok,xfgetc(F));
      }
    } /* else not c=='<' */
  } /* else not in_element */
  log_printf(LOG_ERROR,"Syntax error (should not happen)");
  return XML_ERROR;
}
示例#18
0
文件: token.c 项目: brennie/sexc
void nextToken(FILE *input)
{
	char buffer[FN_NAME_MAX + 1];
	int c;	

	for (c = fgetc(input); IS_WHITESPACE(c); c = fgetc(input));
	
	if (c == EOF)
	{
#ifdef DEBUG
		printf("Got EOF\n");
#endif
		die("EOF Reached");
	}
	
	if (c == '(')
	{	
		lookahead.type = BEGIN;

#ifdef DEBUG
		printf("Got (\n");
#endif
	}
	else if (c == ')')
	{
		lookahead.type = END;

#ifdef DEBUG
		printf("Got )\n");
#endif
	}
	else if (IS_SIGN_PREFIX(c) && isdigit(fpeek(input)) || isdigit(c))
	{
		ungetc(c, input);

		lookahead.type = VALUE;

		fscanf(input, "%lf", &lookahead.value.number);

#ifdef DEBUG
		printf("Got number %f\n", lookahead.value.number);
#endif	
	}
	else
	{
		unsigned pos = 1;
		int index;

		lookahead.type = FUNCTION;

		buffer[0] = c & 0xFF;
			
		memset(buffer + 1, '\0', FN_NAME_MAX);
						
		c = fgetc(input);
		while (!IS_SPECIAL(c) && pos < FN_NAME_MAX)
		{
			buffer[pos++] = c & 0xFF;
			
			c = fgetc(input);
		}
		
		if (pos == FN_NAME_MAX && !IS_SPECIAL(c))
			die("token too long");

		ungetc(c, input);
			
		index = lookupFunction(buffer);

		if (index < 0)
			die("function not found");
		else
			lookahead.value.fnIndex = index;

#ifdef DEBUG
		printf("Got function: %d:%s\n", lookahead.value.fnIndex, buffer);
#endif

	}

}
示例#19
0
int scanFile(FILE *fp){
    if(fp == NULL){
        printf("File could not be found.\n");
        return -1;
    }

    printf("Reading in tokens...");

    while(fpeek(fp) != EOF){
        int tokenStart = fgetc(fp);
        int error = 0;

        //If we read whitespace, continue;
        if(tokenStart == '\n' || tokenStart == '\r' || tokenStart == '\t' ||
           tokenStart == '\v' || tokenStart == ' '){
               continue;
        }

        error = checkSymbols(fp, tokenStart);

        if(error == 4){
           printf("ERROR Invalid symbol '%c'\n", tokenStart);
           exit(4);
        }
        else if(error == 0){
           continue;
        }

        error = checkReservedWords(fp, tokenStart);

        if(error == -1){

           error = checkVariable(fp, tokenStart);

           if(error == 3){
               printf("ERROR Name exceeds 11 characters\n");
               exit(3);
           }
           else if(error == 0){
               continue;
           }
        }
        else if(error == 0){
           continue;
        }

        error = checkNumber(fp, tokenStart);

        if(error == 2){
           printf("ERROR number exceeds 5 digits\n");
           exit(2);
        }
        else if(error == 1){
           printf("ERROR Variables can't start with a letter");
           exit(1);
        }
        else if(error == 0){
           continue;
        }
    }

    createToken("null", 1);
    printf("COMPLETE\n");
    return 0;


}