Exemplo n.º 1
0
int parseline( char* c1, char* c2, char* def)
{

    size_t i = 1000;
    int j, k, l, m;
    int end = 0;
    char c;
    j = k = l = m = 0;

    if(j = fscanf(stdin, " %s", c1))
    {
        while(isspace(c = getchar()))
        {
            if(c == '\n')
            {
                end = 1;
                break;
            }
        }
        m = ungetc(c, stdin);
        if(!end && (k = fscanf(stdin, " %s", c2)))
        {
            while(isspace(c = getchar()))
            {
                if(c == '\n')
                {
                    end = 1;
                    break;
                }
            }
            if(!end)
            {
                m = ungetc(c, stdin);
                l = getline(&def, &i, stdin);
                def[l-1] = '\0';
            }
        }
    }


    if(!strcmp(c1, "add"))
    {
        if(k&&l)
        {
            return 1;
        }
        else return -1;
    }

    else if(!strcmp(c1, "find"))
    {
        if(k)
        {
            if(l)
                return 7;
            else
                return 3;
        }
        else return -3;
    }


    else if(!strcmp(c1, "delete"))
    {
        if(k)
        {
            return 2;
        }
        else return -2;
    }


    else if(!strcmp(c1, "print"))
    {
        return 4;
    }


    else if(!strcmp(c1, "read"))
    {
        if(k)
        {
            return 6;
        }
        else return -5;
    }

    else if(!strcmp(c1, "exit"))
    {
        return 5;
    }
    else if(!strcmp(c1, "test"))
    {
        if(k)
            return 8;
    }

    return -4;

}
Exemplo n.º 2
0
/* The function f_collect() reads a string that has the format of a
 * floating-point number. The function returns as soon as a format-error
 * is encountered, leaving the offending character in the input. This means
 * that 1.el leaves the 'l' in the input queue. Since all detection of
 * format errors is done here, _doscan() doesn't call strtod() when it's
 * not necessary, although the use of the width field can cause incomplete
 * numbers to be passed to strtod(). (e.g. 1.3e+)
 */
static char *
f_collect(register int c, register FILE *stream, register unsigned int width)
{
	register char *bufp = inp_buf;
	int digit_seen = 0;

	if (c == '-' || c == '+') {
		*bufp++ = c;
		if (--width)
			c = getc(stream);
	}

	while (width && isdigit(c)) {
		digit_seen++;
		*bufp++ = c;
		if (--width)
			c = getc(stream);
	}
	if (width && c == '.') {
		*bufp++ = c;
		if(--width)
			c = getc(stream);
		while (width && isdigit(c)) {
			digit_seen++;
			*bufp++ = c;
			if (--width)
				c = getc(stream);
		}
	}

	if (!digit_seen) {
		if (width && c != EOF) ungetc(c, stream);
		return inp_buf - 1;
	}
	else digit_seen = 0;

	if (width && (c == 'e' || c == 'E')) {
		*bufp++ = c;
		if (--width)
			c = getc(stream);
		if (width && (c == '+' || c == '-')) {
			*bufp++ = c;
			if (--width)
				c = getc(stream);
		}
		while (width && isdigit(c)) {
			digit_seen++;
			*bufp++ = c;
			if (--width)
				c = getc(stream);
		}
		if (!digit_seen) {
			if (width && c != EOF) ungetc(c,stream);
			return inp_buf - 1;
		}
	}

	if (width && c != EOF) ungetc(c, stream);
	*bufp = '\0';
	return bufp - 1;
}
Exemplo n.º 3
0
static int test_eof (lua_State *L, FILE *f) {
  int c = getc(f);
  ungetc(c, f);
  lua_pushlstring(L, NULL, 0);
  return (c != EOF);
}
/**

Process the AIFF file.  This method will call processCOMM to handle the COMM section.  
It will mark the position of the sound file so processSSND and getSamplesAIFF can perform correctly. 

**/
File_Data processAIFF(FILE *outfile, FILE* infile){
	int foundComm = 0;
	int foundSSND = 0;
	File_Data data;
	CommonChunk comm;
	SoundDataChunk sdc;
	data.samples = -1;
	data.channels = -1;
	data.sampleRate = -1;
	data.bitDepth = -1;
	data.success = 0;

	char buff[4];


	int i, j;
	for(i = 0; i < 4; i++){
		buff[i] = fgetc(infile);
	}
	flipBytes(buff, 4);
	int y = *((int*)buff);

	for(i = 0; i < 4; i++){
		buff[i] = fgetc(infile);
	}
	if(strncmp(buff, "AIFF", 4) != 0){
		data.success = 0;
		return data;
	}else {
		strncpy(data.format, "AIFF\0", 5);
	}
	while(!foundComm || !foundSSND){
		buff[0] = fgetc(infile);
		if(EOF == buff[0]){
			data.success = 0;
			return data;
		}else if(buff[0] != 'C' && buff[0] != 'S' && buff[0] != 'A'){
			continue;
		}

		for(i = 1; i < 4; i++){
			buff[i] = fgetc(infile);
			if(buff[i] == 'C'){
				ungetc(buff[i], infile);
				continue;
			}
		}
		if(strncmp(buff, "COMM", 4) == 0){
			comm = processComm(infile);
			data.samples = comm.numSampleFrames;
			data.channels = comm.numChannels;
			data.sampleRate = comm.sampleRate;
			data.bitDepth = comm.sampleSize;
			strcpy(data.duration, findDuration(data.sampleRate, data.channels, data.samples, data.duration));
			foundComm = 1;
		}
		if(strncmp(buff, "SSND", 4) == 0){
			/*Marks the position of the SSND chunk so it can be processed later*/
			foundSoundData = fgetpos(infile, &SSNDLocation);
			foundSSND = 1;
		}
		if(strncmp(buff, "COMT", 4) == 0 || strncmp(buff, "ANNO", 4) == 0 ){
			/* Runs through comment chunks */
			int chunkSize;
			char sizeBuff[4];
			for(j = 0; j < 4; j++){
				sizeBuff[j] = fgetc(infile);
			}
			flipBytes(sizeBuff, 4);
			chunkSize = *((int *)sizeBuff);
			int count = 0;
			while(count < chunkSize){
				count++;
				fgetc(infile);
			}

		}
	}
	if(foundSSND && foundComm)
		data.success = 1;
	return data;
}
Exemplo n.º 5
0
static void FILE_from_erlangv(ErlDrvData drv_data,  ErlIOVec* ev)
{
    Desc *desc = (Desc*) drv_data;
    SysIOVec  *iov = ev->iov;
    ErlDrvBinary* bin;

    switch ((&iov[1])->iov_base[0]) {

    case XX_OPEN: {
	char buf[BUFSIZ];
	char file[BUFSIZ];  /* should be FILENAME_MAX */
	char flags[4];       /* at most someething like rb+ */
	char* src;
	char* dst;
	char* src_end;
	char* dst_end;
	int n;

	if (desc->fp != NULL) {
	    driver_error(desc->port, XX_EINVAL);
	    return;
	}

	/* play it safe ? */
	n = vec_to_buf(ev, buf, BUFSIZ);
	src = buf + 1;
	src_end = buf + n;

	/* get file name */
	dst = file;
	dst_end = dst + BUFSIZ;  /* make room for a '\0' */
	while((src < src_end) && (dst < dst_end) && (*src != '\0'))
	    *dst++ = *src++;
	if ((src == src_end) || (dst == dst_end)) {
	    driver_error(desc->port, XX_EINVAL);
	}
	*dst = *src++;
	/* get flags */
	dst = flags;
	dst_end = dst + 4;
	while((src < src_end) && (dst < dst_end) && (*src != '\0'))
	    *dst++ = *src++;	
	if (dst == dst_end) {
	    driver_error(desc->port, XX_EINVAL);
	    return;
	}
	*dst = '\0';

	if ((desc->fp = fopen(file, flags))==NULL) {
	    driver_error(desc->port, errno);
	    return;
	}
	driver_ok(desc->port);
	break;
    }

    case XX_WRITE: {
	int i;
	iov[1].iov_base++;
	iov[1].iov_len--;
	for(i=1; i<ev->vsize; i++) {
	    if (fwrite(iov[i].iov_base, 1, iov[i].iov_len, desc->fp) !=
		iov[i].iov_len) {
		driver_error(desc->port, errno);
		return;
	    }
	}
	driver_ok(desc->port);
	break;
    }

    case XX_READ: {
	char ch = XX_VALUE;
	int rval;
	int sz = get_int32((&iov[1])->iov_base+1);

	if ((bin = driver_alloc_binary(sz)) == NULL) {
	    driver_error(desc->port, -1);
	    return;
	}

	if ((rval = fread(bin->orig_bytes, 1, sz, desc->fp)) != sz) {
	    if (feof(desc->fp)) {
		if (rval == 0) {
		    driver_free_binary(bin);
		    driver_eof(desc->port);
		    return;
		}
		driver_output_binary(desc->port, &ch, 1,bin, 0, rval);
		driver_free_binary(bin);
		return;
	    }
	    driver_free_binary(bin);
	    driver_error(desc->port, errno);
	    return;
	}
	driver_output_binary(desc->port, &ch, 1,bin, 0, sz);
	driver_free_binary(bin);
	break;
    }

    case XX_SEEK: {
	int offs = get_int32((&iov[1])->iov_base+1);
	int w = (int) (&iov[1])->iov_base[5];
	int whence;
	switch (w) {
	case 1: whence = SEEK_SET; break;
	case 2: whence = SEEK_CUR; break;
	case 3: whence = SEEK_END; break;
	}
	if ((w = fseek(desc->fp, offs, whence)) != 0) {
	    driver_error(desc->port, errno);
	    return;
	}
	driver_ok(desc->port);
	return;
    }

    case XX_TELL: {
	int offs;
	if ((offs = ftell(desc->fp)) == -1) {
	    driver_error(desc->port, errno);
	    return;
	}
	driver_ret32(desc->port, offs);
	break;
    }

    case XX_TRUNCATE: {
        int fno;
        int offs;
	/* is this really safe? */
        if (fflush(desc->fp) != 0) {
	    driver_error(desc->port, errno);
	    return;
	}
	if ((offs = ftell(desc->fp)) == -1) {
	    driver_error(desc->port, errno);
	    return;
	}
        fno = fileno(desc->fp);
#ifdef WIN32
	if (SetEndOfFile((HANDLE)fno) !=  0) {
	    driver_error(desc->port, GetLastError());
	    return;
	}
#else
        if (ftruncate(fno, offs) == -1) {
	    driver_error(desc->port, errno);
	    return;
	}
#endif
	driver_ok(desc->port);
	return;
    }

    case XX_FLUSH:
	if (fflush(desc->fp) != 0)
	    driver_error(desc->port, errno);
	else
	    driver_ok(desc->port);
	break;

    case XX_OEOF:
	if (feof(desc->fp))
	    driver_ret32(desc->port, 1);
	else
	    driver_ret32(desc->port,0);
	break;

    case XX_ERROR:
	if (ferror(desc->fp))
	    driver_ret32(desc->port, 1);
	else
	    driver_ret32(desc->port,0);
	break;

    case XX_GETC: {
	int ch;
	if ((ch = getc(desc->fp)) == EOF) {
	    if (feof(desc->fp)) {
		driver_eof(desc->port);
		return;
	    }
	    driver_error(desc->port, errno);
	    return;
	}
	driver_ret32(desc->port, ch);
	break;
    }

    case XX_SET_LINEBUF_SIZE: {
	int sz = get_int32((&iov[1])->iov_base+1);
	desc->linebuf_size = sz;
	driver_ok(desc->port);
	break;
    }

    case XX_GETS:
    case XX_GETS2: {
	int rval;
	long cpos1, cpos2;
	char header;
	
	if ((bin = driver_alloc_binary(desc->linebuf_size)) == NULL) {
	    driver_error(desc->port, -1);
	    return;
	}

	if ((cpos1 = ftell(desc->fp)) == -1) {
	    driver_free_binary(bin);
	    driver_error(desc->port, errno);
	    return;
	}

	if ((fgets(bin->orig_bytes, desc->linebuf_size,
		   desc->fp)) == NULL) {
	    driver_free_binary(bin);
	    if (feof(desc->fp)) {
		driver_eof(desc->port);
		return;
	    }
	    driver_error(desc->port, errno);
	    return;
	}
	if ((cpos2 = ftell(desc->fp)) == -1) {
	    driver_free_binary(bin);
	    driver_error(desc->port, errno);
	    return;
	}
	rval = cpos2 - cpos1;

	if (bin->orig_bytes[rval-1] == '\n' &&
	    bin->orig_bytes[rval] == 0) {
	    header = XX_FLINE;
	    /* GETS keep newline, GETS2 remove newline */
	    rval = rval - ((&iov[1])->iov_base[0] == XX_GETS ? 0 : 1);
	}
	else
	    header = XX_NOLINE;
	driver_output_binary(desc->port, &header, 1,bin, 0, rval);
	driver_free_binary(bin);
	break;
    }

    case XX_UNGETC: {
	int ch = (&iov[1])->iov_base[1];
	if (ungetc(ch, desc->fp) == EOF)
	    driver_error(desc->port, errno);
	else
	    driver_ok(desc->port);
	break;
    }
    
    default:
#ifdef DEBUG
	fprintf(stderr, "Unknown opcode %c\n\r", ((&iov[1])->iov_base[0]));
#endif
	driver_error(desc->port, XX_EINVAL);
	break;
    }
	
	
}
Exemplo n.º 6
0
csdbparser::enResult csdbparser::symbolread(sym_data *data, symdata_pack* pack)
{
    if (m_debug) printf("=====> symbolread\n");
    int ch, ch2;
    data->clear();
    data->valid = true;
    data->sym_type = sym_data::symNone;
    ch = fgetc(m_fp);
    if (m_debug) printf("check3!  %c\n", (char)ch);
    if (ch == 9) // TAB
    {
        ch = fgetc(m_fp);
        if (m_debug) printf("check4!  %c\n", (char)ch);
        switch (ch)
        {
        case '}': // end of func
            if (m_calling_func.size() > 0)
                m_calling_func.clear();
            else if (m_debug) printf("no func to clear!\n");
            data->valid = false;
            if (m_debug) printf("End of func found\n");
            break;
        case ')': // end of macro
            if (m_calling_macro.size() > 0)
                m_calling_macro.clear();
            else if (m_debug) printf("no macro to clear!\n");
            data->valid = false;
            if (m_debug) printf("End of macro found\n");
            break;
        case '~': // include
            ch2 = fgetc(m_fp);
            if ((ch2 == '"')||(ch2 == '<'))
            {
                pack->line_text += (char) ch2;
            }
            else
            {
                ungetc(ch2, m_fp);
            }
            data->sym_type = sym_data::symIncl;
            if (m_debug) printf("Incl found\n");
            break;
        default:
            for (int i=0; i<symbtypetbl_SIZE; i++)
            {
                if (symbtypetbl[i].chr == ch)
                {
                    data->sym_type =
                        symbtypetbl[i].type;
                    break;
                }
            }
            if (data->sym_type == sym_data::symNone)
                return resUNKNOWN_ERR;
            break;
        };
    }
    else ungetc(ch, m_fp);
    if (fgets(m_buf, m_bufsize, m_fp) == NULL)
    {
        return resFILE_ACCESS_ERR;
    }
    data->symbname = chomp(m_buf);
    if (data->valid) data->valid = (strlen(data->symbname.c_str()) > 0);
    if (m_debug) printf("sym name=%s, type = %s, valid=%d, ch=%c\n",
                            data->symbname.c_str(), data->getTypeDesc(), data->valid, ch);
    if      (ch == '$')
    {
        m_calling_func.assign(data->symbname);
    }
    else if (ch == '#')
    {
        m_calling_macro.assign(data->symbname);
    }
    else if (ch == '`')
    {
        data->calling_func = m_calling_func;
        data->calling_macro = m_calling_macro;
    }
    return resOK;
}
Exemplo n.º 7
0
Arquivo: rc.c Projeto: svn2github/xqf
static inline int rc_ungetc (char c, FILE *rc) {
  pos--;
  return ungetc (c, rc);
}
Exemplo n.º 8
0
/* Extract from the stream the longest string of characters which are neither
   whitespace nor brackets (except for an optional bracketed n-char_sequence
   directly following nan or @[email protected] independently of case).
   The user must free the returned string.                                    */
static char *
extract_string (FILE *stream)
{
  int c;
  size_t nread = 0;
  size_t strsize = 100;
  char *str = mpc_alloc_str (strsize);
  size_t lenstr;

  c = getc (stream);
  while (c != EOF && c != '\n'
         && !isspace ((unsigned char) c)
         && c != '(' && c != ')') {
    str [nread] = (char) c;
    nread++;
    if (nread == strsize) {
      str = mpc_realloc_str (str, strsize, 2 * strsize);
      strsize *= 2;
    }
    c = getc (stream);
  }

  str = mpc_realloc_str (str, strsize, nread + 1);
  strsize = nread + 1;
  str [nread] = '\0';

  if (nread == 0)
    return str;

  lenstr = nread;

  if (c == '(') {
    size_t n;
    char *suffix;
    int ret;

    /* (n-char-sequence) only after a NaN */
    if ((nread != 3
         || tolower ((unsigned char) (str[0])) != 'n'
         || tolower ((unsigned char) (str[1])) != 'a'
         || tolower ((unsigned char) (str[2])) != 'n')
        && (nread != 5
            || str[0] != '@'
            || tolower ((unsigned char) (str[1])) != 'n'
            || tolower ((unsigned char) (str[2])) != 'a'
            || tolower ((unsigned char) (str[3])) != 'n'
            || str[4] != '@')) {
      ungetc (c, stream);
      return str;
    }

    suffix = extract_suffix (stream);
    nread += strlen (suffix) + 1;
    if (nread >= strsize) {
      str = mpc_realloc_str (str, strsize, nread + 1);
      strsize = nread + 1;
    }

    /* Warning: the sprintf does not allow overlap between arguments. */
    ret = sprintf (str + lenstr, "(%s", suffix);
    MPC_ASSERT (ret >= 0);
    n = lenstr + (size_t) ret;
    MPC_ASSERT (n == nread);

    c = getc (stream);
    if (c == ')') {
      str = mpc_realloc_str (str, strsize, nread + 2);
      strsize = nread + 2;
      str [nread] = (char) c;
      str [nread+1] = '\0';
      nread++;
    }
    else if (c != EOF)
      ungetc (c, stream);

    mpc_free_str (suffix);
  }
  else if (c != EOF)
    ungetc (c, stream);

  return str;
}
Exemplo n.º 9
0
void StdioUngetc(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs) 
{
	UNUSED(Parser); UNUSED(NumArgs);
    ReturnValue->Val->Integer = ungetc(Param[0]->Val->Integer, (FILE *) Param[1]->Val->Pointer);
}
Exemplo n.º 10
0
MFModifiedPolytope MFReadPolytopeFromPlotfile(FILE *fid, int k, int dimV, MFErrorHandler e)
 {
  static char RoutineName[]={"MFReadPolytopeFromPlotfile"};
  MFModifiedPolytope P;
  int mV,iV,iV0;
  double *v;
  int *vt;
  int mE,iE;
  int *ev;
  int *et;
  int mF,iF;
  int *nfv;
  int **fv;
  int *ft;
  int i,j,l,n;
  int ipoly,nv,ne,nf;
  int verbose=0;
  int iv,ie,iE0,je,np,v0,v1;
  int trip;
  int sing,bnd;
  char c;
  double R;

  if(verbose){printf("     Read Polytope\n");fflush(stdout);}
  P=(MFModifiedPolytope)malloc(sizeof(struct MFModifiedPolytopeSt));
  P->k=k;
  P->dimV=dimV;

  fscanf(fid,"Polyhedron %d, ",&ipoly);
  if(verbose){printf("          Polytope %d\n",ipoly);fflush(stdout);}
  c=fgetc(fid);
  ungetc(c,fid);
  if(c=='R')
   {
    fscanf(fid,"R=%lf, %d vertices, %d edges, %d faces,  boundary %d, singular %d\n",&R,&nv,&ne,&nf,&bnd,&sing);
   }else{
    fscanf(fid,"%d vertices, %d edges, %d faces,  boundary %d, singular %d\n",&nv,&ne,&nf,&bnd,&sing);
    R=0;
   }
  fscanf(fid,"  %d vertices, %d edges, %d faces,  boundary %d, singular %d\n",nv,ne,nf,bnd,sing);

  P->n=nv;
  P->m=nv;
  P->v=(double*)malloc(P->n*dimV*sizeof(double));
  P->nIndices=(int*)malloc(P->n*sizeof(int));
  P->mIndices=(int*)malloc(P->n*sizeof(int));
  P->indices=(int**)malloc(P->n*sizeof(int*));
  P->mark=(int*)malloc(P->n*sizeof(int));
  for(i=0;i<P->n;i++)
   {
    P->nIndices[i]=0;
    P->mIndices[i]=0;
    P->indices[i]=(int*)NULL;
    P->mark[i]=0;
   }

  if(verbose){printf("Polyhedron %d, %d vertices, %d edges, %d faces\n",ipoly,nv,ne,nf);fflush(stdout);}

  for(iv=0;iv<nv;iv++)
   {
    fscanf(fid,"Vertex %d (%lf",&iV,&(P->v[0+P->dimV*iv]));
    if(verbose){printf("Vertex %d (%lf",iV,(P->v[0+P->dimV*iv]));fflush(stdout);}
    for(i=1;i<dimV;i++){fscanf(fid,",%lf",&(P->v[i+P->dimV*iv]));if(verbose){printf(",%lf",(P->v[i+P->dimV*iv]));fflush(stdout);}}
    fscanf(fid,"), %d ",&(P->nIndices[iv]));
    if(verbose){printf("), %d ",(P->nIndices[iv]));fflush(stdout);}
    P->mIndices[iv]=P->nIndices[iv];
    if(P->nIndices[iv]!=0)
     {
      P->indices[iv]=(int*)malloc((P->nIndices[i])*sizeof(int));

      fscanf(fid,"[%d",&(P->indices[iv][0]));
      if(verbose){printf(    "[%d", (P->indices[iv][0]));fflush(stdout);}

      for(i=1;i<P->nIndices[iv];i++)
       {
        fscanf(fid,",%d",&(P->indices[iv][i]));
        if(verbose){printf(    ",%d", (P->indices[iv][i]));fflush(stdout);}
       }

      fscanf(fid,"]\n");
      if(verbose){printf(    "]\n");fflush(stdout);}
     }else{
      fscanf(fid," [ ]\n");
      if(verbose){printf(    "\n");fflush(stdout);}
     }

    if(verbose)
     {
      printf("  Vertex %d (%lf",iv,P->v[0+P->dimV*iV]);
      for(i=1;i<P->dimV;i++)printf(",%lf",P->v[i+P->dimV*iV]);
      printf(")\n");fflush(stdout);
     }
   }


  for(ie=0;ie<ne;ie++)
   {
    if(k>1)
     {
      fscanf(fid,"Edge %d (%d,%d), %*d [%*[ 0-9+-.,]]\n",&iE,&v0,&v1);
      if(verbose){printf(    "Edge %d (%d,%d)\n",iE,v0,v1);fflush(stdout);}
     }else if(k==1)
     {
      fscanf(fid,"Edge %d (%d,%d), %*d []\n",&iE,&v0,&v1);
      if(verbose){printf(    "Edge %d (%d,%d)\n",iE,v0,v1);fflush(stdout);}
     }else{
      fscanf(fid,"Edge %d (%d,%d), %*d [%*[ 0-9+-.,]]\n",&iE,&v0,&v1);
      if(verbose){printf(    "Edge %d (%d,%d)\n",iE,v0,v1);fflush(stdout);}
     }
    if(verbose){printf("  Edge %d (%d,%d)\n",ie,v0,v1);fflush(stdout);}
   }

  P->nFaces=nf;
  P->mFaces=nf;
  P->face  =(int*)malloc(P->mFaces*sizeof(int));
  P->nFaceV=(int*)malloc(P->mFaces*sizeof(int));
  P->faceN =(MFNVector*)malloc(P->mFaces*sizeof(MFNVector));
  P->faceO =(double*)malloc(P->mFaces*sizeof(double));

  for(i=0;i<nf;i++)
   {
    fscanf(fid,"Face %d neighbor %*d\n",&(P->face[i]));
    if(verbose){printf(    "Face %d neighbor\n",(P->face[i]));fflush(stdout);}
    P->nFaceV[i]=0;
    P->faceN [i]=(MFNVector)NULL;
    P->faceO [i]=0.;
   }
  if(verbose){printf("done\n");fflush(stdout);}

  return P;
 }
Exemplo n.º 11
0
int
mpc_inp_str (mpc_ptr rop, FILE *stream, size_t *read, int base,
mpc_rnd_t rnd_mode)
{
   size_t white, nread = 0;
   int inex = -1;
   int c;
   char *str;

   if (stream == NULL)
      stream = stdin;

   white = skip_whitespace (stream);
   c = getc (stream);
   if (c != EOF) {
     if (c == '(') {
       char *real_str;
       char *imag_str;
       size_t n;
       int ret;

       nread++; /* the opening parenthesis */
       white = skip_whitespace (stream);
       real_str = extract_string (stream);
       nread += strlen(real_str);

       c = getc (stream);
       if (!isspace ((unsigned int) c)) {
         if (c != EOF)
           ungetc (c, stream);
         mpc_free_str (real_str);
         goto error;
       }
       else
         ungetc (c, stream);

       white += skip_whitespace (stream);
       imag_str = extract_string (stream);
       nread += strlen (imag_str);

       str = mpc_alloc_str (nread + 2);
       ret = sprintf (str, "(%s %s", real_str, imag_str);
       MPC_ASSERT (ret >= 0);
       n = (size_t) ret;
       MPC_ASSERT (n == nread + 1);
       mpc_free_str (real_str);
       mpc_free_str (imag_str);

       white += skip_whitespace (stream);
       c = getc (stream);
       if (c == ')') {
         str = mpc_realloc_str (str, nread +2, nread + 3);
         str [nread+1] = (char) c;
         str [nread+2] = '\0';
         nread++;
       }
       else if (c != EOF)
         ungetc (c, stream);
     }
     else {
       if (c != EOF)
         ungetc (c, stream);
       str = extract_string (stream);
       nread += strlen (str);
     }

     inex = mpc_set_str (rop, str, base, rnd_mode);

     mpc_free_str (str);
   }

error:
   if (inex == -1) {
      mpfr_set_nan (mpc_realref(rop));
      mpfr_set_nan (mpc_imagref(rop));
   }
   if (read != NULL)
     *read = white + nread;
   return inex;
}
Exemplo n.º 12
0
/**
 * Reads strings from a file and computes the frequencies of the characters.
 * @param in File to read from
 * @param freq Where to store computed frequencies
 * @param total_length If not NULL, the total number of characters is stored here
 * @return The resulting list of strings
 */
string_list_t *read_strings(FILE *in, int ignore_case, int *freq,
                            int *total_length, int *string_count)
{
    unsigned char *buf;
    string_list_t *head;
    string_list_t **nextp;
    int max_len;
    int i;
    if (string_count)
        *string_count = 0;

    /* Zap frequency counts. */
    for (i = 0; i < 256; i++)
        freq[i] = 0;

    /* Read strings and count character frequencies as we go. */
    head = NULL;
    nextp = &head;
    max_len = 64;
    buf = (unsigned char *)malloc(max_len);
    if (total_length)
        *total_length = 0;
    while (!feof(in)) {
        /* Read one string (all chars until STRING_SEPARATOR) into temp buffer */
        int c;
        int in_comment = 0;
        i = 0;
        while (((c = fgetc(in)) != -1) && (c != STRING_SEPARATOR)) {
            if (c == '\\') {
                /* Check for line escape */
                int d;
                d = fgetc(in);
                if (d == STRING_SEPARATOR) {
                    continue;
                } else if (d == '#') {
                    c = '#';
                } else {
                    ungetc(d, in);
                }
            } else if ((i == 0) && (c == '#')) {
                in_comment = 1;
	    }
            if (in_comment)
                continue;
            if (i == max_len) {
                /* Allocate larger buffer */
                max_len += 64;
                buf = (unsigned char *)realloc(buf, max_len);
            }
            if (ignore_case && (c >= 'A') && (c <= 'Z'))
                c += 0x20;
            buf[i++] = (unsigned char)c;
            freq[c]++;
        }

        if (i > 0) {
            /* Add string to list */
            string_list_t *lst = (string_list_t *)malloc(sizeof(string_list_t));
            lst->text = (unsigned char *)malloc(i+1);
            lst->huff_data = 0;
            lst->huff_size = 0;
            memcpy(lst->text, buf, i);
            lst->text[i] = 0;
            lst->next = NULL;
            *nextp = lst;
            nextp = &(lst->next);
            if (total_length)
                *total_length = *total_length + i;
            if (string_count)
                *string_count = *string_count + 1;
        }
    }
    free(buf);
    return head;
}
Exemplo n.º 13
0
BOOL LLWearable::importFile( LLFILE* file )
{
	// *NOTE: changing the type or size of this buffer will require
	// changes in the fscanf() code below. You would be better off
	// rewriting this to use streams and not require an open FILE.
	char text_buffer[2048];		/* Flawfinder: ignore */
	S32 fields_read = 0;

	// read header and version 
	fields_read = fscanf( file, "LLWearable version %d\n", &mDefinitionVersion );
	if( fields_read != 1 )
	{
		// Shouldn't really log the asset id for security reasons, but
		// we need it in this case.
		llwarns << "Bad Wearable asset header: " << mAssetID << llendl;
		//gVFS->dumpMap();
		return FALSE;
	}

	if( mDefinitionVersion > LLWearable::sCurrentDefinitionVersion )
	{
		llwarns << "Wearable asset has newer version (" << mDefinitionVersion << ") than XML (" << LLWearable::sCurrentDefinitionVersion << ")" << llendl;
		return FALSE;
	}

	// name
	char next_char = fgetc( file );		/* Flawfinder: ignore */
	if( '\n' == next_char )
	{
		// no name
		mName = "";
	}
	else
	{
		ungetc( next_char, file );
		fields_read = fscanf(	/* Flawfinder: ignore */
			file,
			"%2047[^\n]",
			text_buffer);
		if( (1 != fields_read) || (fgetc( file ) != '\n') )		/* Flawfinder: ignore */
		{
			llwarns << "Bad Wearable asset: early end of file" << llendl;
			return FALSE;
		}
		mName = text_buffer;
		LLStringUtil::truncate(mName, DB_INV_ITEM_NAME_STR_LEN );
	}

	// description
	next_char = fgetc( file );		/* Flawfinder: ignore */
	if( '\n' == next_char )
	{
		// no description
		mDescription = "";
	}
	else
	{
		ungetc( next_char, file );
		fields_read = fscanf(	/* Flawfinder: ignore */
			file,
			"%2047[^\n]",
			text_buffer );
		if( (1 != fields_read) || (fgetc( file ) != '\n') )		/* Flawfinder: ignore */
		{
			llwarns << "Bad Wearable asset: early end of file" << llendl;
			return FALSE;
		}
		mDescription = text_buffer;
		LLStringUtil::truncate(mDescription, DB_INV_ITEM_DESC_STR_LEN );
	}

	// permissions
	S32 perm_version;
	fields_read = fscanf( file, " permissions %d\n", &perm_version );
	if( (fields_read != 1) || (perm_version != 0) )
	{
		llwarns << "Bad Wearable asset: missing permissions" << llendl;
		return FALSE;
	}
	if( !mPermissions.importFile( file ) )
	{
		return FALSE;
	}

	// sale info
	S32 sale_info_version;
	fields_read = fscanf( file, " sale_info %d\n", &sale_info_version );
	if( (fields_read != 1) || (sale_info_version != 0) )
	{
		llwarns << "Bad Wearable asset: missing sale_info" << llendl;
		return FALSE;
	}
	// Sale info used to contain next owner perm. It is now in the
	// permissions. Thus, we read that out, and fix legacy
	// objects. It's possible this op would fail, but it should pick
	// up the vast majority of the tasks.
	BOOL has_perm_mask = FALSE;
	U32 perm_mask = 0;
	if( !mSaleInfo.importFile(file, has_perm_mask, perm_mask) )
	{
		return FALSE;
	}
	if(has_perm_mask)
	{
		// fair use fix.
		if(!(perm_mask & PERM_COPY))
		{
			perm_mask |= PERM_TRANSFER;
		}
		mPermissions.setMaskNext(perm_mask);
	}

	// wearable type
	S32 type = -1;
	fields_read = fscanf( file, "type %d\n", &type );
	if( fields_read != 1 )
	{
		llwarns << "Bad Wearable asset: bad type" << llendl;
		return FALSE;
	}
	if( 0 <= type && type < WT_COUNT )
	{
		mType = (EWearableType)type;
	}
	else
	{
		llwarns << "Bad Wearable asset: bad type #" << type <<  llendl;
		return FALSE;
	}


	// parameters header
	S32 num_parameters = 0;
	fields_read = fscanf( file, "parameters %d\n", &num_parameters );
	if( fields_read != 1 )
	{
		llwarns << "Bad Wearable asset: missing parameters block" << llendl;
		return FALSE;
	}

	// parameters
	S32 i;
	for( i = 0; i < num_parameters; i++ )
	{
		S32 param_id = 0;
		F32 param_weight = 0.f;
		fields_read = fscanf( file, "%d %f\n", &param_id, &param_weight );
		if( fields_read != 2 )
		{
			llwarns << "Bad Wearable asset: bad parameter, #" << i << llendl;
			return FALSE;
		}
		mVisualParamMap[param_id] = param_weight;
	}

	// textures header
	S32 num_textures = 0;
	fields_read = fscanf( file, "textures %d\n", &num_textures);
	if( fields_read != 1 )
	{
		llwarns << "Bad Wearable asset: missing textures block" << llendl;
		return FALSE;
	}

	// textures
	for( i = 0; i < num_textures; i++ )
	{
		S32 te = 0;
		fields_read = fscanf(	/* Flawfinder: ignore */
			file,
			"%d %2047s\n",
			&te, text_buffer);
		if( fields_read != 2 )
		{
			llwarns << "Bad Wearable asset: bad texture, #" << i << llendl;
			return FALSE;
		}

		if( !LLUUID::validate( text_buffer ) )
		{
			llwarns << "Bad Wearable asset: bad texture uuid: " << text_buffer << llendl;
			return FALSE;
		}

		mTEMap[te] = LLUUID(text_buffer );
	}

	return TRUE;
}
Exemplo n.º 14
0
static void fp_ungetc(int c, struct tok_state *tok) {
    ungetc(c, tok->fp);
}
Exemplo n.º 15
0
void
input_file_open (char *filename, /* "" means use stdin. Must not be 0.  */
		 int pre)
{
  int c;
  char buf[80];

  preprocess = pre;

  assert (filename != 0);	/* Filename may not be NULL.  */
  if (filename[0])
    {
      f_in = fopen (filename, FOPEN_RT);
      file_name = filename;
    }
  else
    {
      /* Use stdin for the input file.  */
      f_in = stdin;
      /* For error messages.  */
      file_name = _("{standard input}");
    }

  if (f_in)
    c = getc (f_in);

  if (f_in == NULL || ferror (f_in))
    {
#ifdef BFD_ASSEMBLER
      bfd_set_error (bfd_error_system_call);
#endif
      as_perror (_("Can't open %s for reading"), file_name);

      if (f_in)
	{
	  fclose (f_in);
	  f_in = NULL;
	}
      return;
    }

  if (c == '#')
    {
      /* Begins with comment, may not want to preprocess.  */
      c = getc (f_in);
      if (c == 'N')
	{
	  fgets (buf, 80, f_in);
	  if (!strncmp (buf, "O_APP", 5) && ISSPACE (buf[5]))
	    preprocess = 0;
	  if (!strchr (buf, '\n'))
	    ungetc ('#', f_in);	/* It was longer.  */
	  else
	    ungetc ('\n', f_in);
	}
      else if (c == 'A')
	{
	  fgets (buf, 80, f_in);
	  if (!strncmp (buf, "PP", 2) && ISSPACE (buf[2]))
	    preprocess = 1;
	  if (!strchr (buf, '\n'))
	    ungetc ('#', f_in);
	  else
	    ungetc ('\n', f_in);
	}
      else if (c == '\n')
	ungetc ('\n', f_in);
      else
	ungetc ('#', f_in);
    }
  else
    ungetc (c, f_in);
}
Exemplo n.º 16
0
int main()
{
    FILE *pascal_file,*lex_file;
    char file_name[40], file_name2[40];
    char is_token[40];
    char current_char;
    char before_current_char;
    int i=0,j,is_comment=0,is_assignment=0;
    printf("Please enter the source file name: ");
    fflush(stdin);
    gets(file_name);
    strcpy(file_name2,file_name);
    strcat(file_name,".pas");
    strcat(file_name2,".lex");


    for(j=0;j<40;j++)
        is_token[j]=0;
    if((pascal_file = fopen(file_name,"r")) == NULL)
        printf("dosya acilamadi!\n");
    else
    {
        lex_file = fopen(file_name2,"w");
        while(!feof(pascal_file))
        {

            current_char=getc(pascal_file);
            if(isLetter(current_char)==1)//current_char harfse string e eklenir
            {
                is_token[i]=current_char;
                i++;
            }
            else if(isLetter(current_char)==0 && i!=0)// current char harf degilse ondan onceki stringi(is_letter) yazdýr
            {
                if(strcmp("writeln",is_token)==0 || strcmp("write",is_token)==0)
                {
                    fputs("output(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(strcmp("readln",is_token)==0 || strcmp("read",is_token)==0)
                {
                    fputs("input(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(isReservedWord(is_token)==1)
                {
                    fputs("reservedWord(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(isAdvMathFunc(is_token)==1)
                {
                    fputs("advancedMathFunction(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(isOrdinalFunc(is_token)==1)
                {
                    fputs("ordinalFunction(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(isVariableType(is_token)==1)
                {
                    fputs("variableType(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(isBoolOperator(is_token)==1)
                {
                    fputs("booleanOperator(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(isFileHandlingFunc(is_token)==1)
                {
                    fputs("fileHandlingFunction(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else if(strcmp(is_token,"div")==0 || strcmp(is_token,"mod")==0)
                {
                    fputs("arithmeticOperation(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                else
                {
                    fputs("variable(",lex_file);
                    fputs(is_token,lex_file);
                    fputs("),",lex_file);
                }
                i=0;
                for(j=0;j<40;j++)
                    is_token[j]=0;
            }

            if(current_char==':')
            {
                current_char=getc(pascal_file);
                if(current_char=='=')
                {
                    fputs("assignmentOperator(:=),",lex_file);
                    is_assignment=1;
                }
                else
                {
                    fputs("colon(:),",lex_file);
                    ungetc(current_char,pascal_file);
                }
            }


            if(current_char=='{')
            {
                comment(pascal_file,current_char,lex_file);
            }


            if(current_char=='*' && is_comment==1)
            {
                comment(pascal_file,current_char,lex_file);
                is_comment=0;
            }
            if(is_comment==1)
            {
                fputs("leftParentheses((),",lex_file);
            }
            if(current_char==')')
            {
                fputs("rightParentheses()),",lex_file);
            }
            if(current_char==';')
            {
                fputs("endOfLine(;),",lex_file);
            }
            if(current_char=='[')
            {
                fputs("openingBracket([)",lex_file);
            }
            if(current_char==']')
            {
                fputs("closingBracket(])",lex_file);
            }



           if(is_assignment==0 && (current_char=='<' || current_char=='>' || current_char=='='))
            {
                before_current_char=current_char;
                current_char=getc(pascal_file);
                if(before_current_char=='<' && (current_char=='=' || current_char=='>'))
                {
                    fputs("compOperator(",lex_file);
                    fputc(before_current_char,lex_file);
                    fputc(current_char,lex_file);
                    fputs("),",lex_file);
                }
                else if(before_current_char=='>' && current_char=='=')
                {
                    fputs("compOperator(",lex_file);
                    fputc(before_current_char,lex_file);
                    fputc(current_char,lex_file);
                    fputs("),",lex_file);
                }
                else if(before_current_char=='<' || before_current_char=='>' || before_current_char=='=')
                {
                    fputs("compOperator(",lex_file);
                    fputc(before_current_char,lex_file);
                    fputs("),",lex_file);
                    ungetc(current_char,pascal_file);
                }

            }
            is_assignment=0;




            if(current_char=='+' || current_char =='-' || current_char=='*' || current_char=='/')
            {
                fputs("arithOperator(",lex_file);
                fputc(current_char,lex_file);
                fputs("),",lex_file);
            }

            is_comment=0;
            if(current_char=='(')
            {
                is_comment=1;
            }
            if(current_char==39)
            {
                skip_string(pascal_file,lex_file);
            }

            if(current_char==9 || current_char==10 || current_char==' ')
            {
                fputc(current_char,lex_file);
            }
            /*if(current_char==';')
            {

                i=0;
                for(j=0;j<40;j++)
                    is_token[j]='\0';
            }*/
            if(isNumeric(current_char)==1)
            {
                constant(pascal_file,lex_file,current_char);
            }

        }
        fclose(lex_file);
        lex_file = fopen(file_name2,"r");
        current_char=getc(lex_file);
        while(!feof(lex_file))
        {
            printf("%c",current_char);
            current_char=getc(lex_file);
        }
    }

    return 0;
}
Exemplo n.º 17
0
csdbparser::enResult csdbparser::get_next_symbol(symdata_pack* pack)
{
    CSDBP_GENERAL_CHK();
    enResult res;
    bool endOfSymbData;
    bool foundSomething;
    int ch;

//if (m_state != stSYMB_SETUP_DONE) return resUNKNOWN_ERR;

    pack->clear();
    if (m_debug) printf("=====> get_next_symbol\n");
    do
    {
        res = single_line_symbol(endOfSymbData, foundSomething);
        if (res != resOK) return res;
        if (endOfSymbData)
        {
            pack->valid = false;
            if (m_debug) printf("End of symbols data!\n");
            return resOK;
        }
    }
    while (foundSomething);
    pack->valid = true;
    pack->filename = m_current_srcfile;
    if (m_debug) printf("=====> Back from get_next_symbol\n");

    ch = fgetc(m_fp);
    if (ch == 0x0A)
    {
        pack->line_num = -1; // empty line
        return resOK; //EOL
    }
    else ungetc(ch, m_fp);

    if (fscanf(m_fp, "%ld", &(pack->line_num)) != 1)
    {
        return resUNKNOWN_ERR;
    }
    ch = fgetc(m_fp); // the space after the line number
    if (fgets(m_buf, m_bufsize, m_fp) == NULL)
    {
        return resFILE_ACCESS_ERR;
    }
    pack->line_text = chomp(m_buf);
    if (m_debug)
    {
        printf("fn = %s, lineno=%ld, firstline=%s\n",
               pack->filename.c_str(), pack->line_num, pack->line_text.c_str());
    }

    int loopcheck = 0; // prevent infinite loop
    sym_data sd;
    while (loopcheck++ < 65500)
    {
        // symbol line
        ch = fgetc(m_fp);
        if ((ch == 0x0A)&&(loopcheck > 1))
        {
            break; //EOL
        }
        else if ((ch >= 0x30)&&(ch <= 0x39)&&(loopcheck > 1))
        {
            ungetc(ch, m_fp);
            break; // symbol shouldn't start with line numbers
        }
        else
        {
            ungetc(ch, m_fp);
            res = symbolread(&sd, pack);
            if (res != resOK) return res;
            pack->line_text += sd.symbname;
            if (sd.valid)
            {
                pack->symbols.push_back(sd);
            }
        }
        // no-symbol line
        ch = fgetc(m_fp);
        if ((ch == 0x0A)&&(loopcheck > 1))
        {
            ;
        }
        else
        {
            ungetc(ch, m_fp);
            if (fgets(m_buf, m_bufsize, m_fp) == NULL)
            {
                return resFILE_ACCESS_ERR;
            }
            pack->line_text += chomp(m_buf);
        }
    }
    return resOK;
}
Exemplo n.º 18
0
boolean faReadMixedNext(FILE *f, boolean preserveCase, char *defaultName, 
    boolean mustStartWithComment, char **retCommentLine, struct dnaSeq **retSeq)
/* Read next sequence from .fa file. Return sequence in retSeq.  
 * If retCommentLine is non-null return the '>' line in retCommentLine.
 * The whole thing returns FALSE at end of file. 
 * Contains parameter to preserve mixed case. */
{
char lineBuf[1024];
int lineSize;
char *words[1];
int c;
off_t offset = ftello(f);
size_t dnaSize = 0;
DNA *dna, *sequence;
char *name = defaultName;

if (name == NULL)
    name = "";
dnaUtilOpen();
if (retCommentLine != NULL)
    *retCommentLine = NULL;
*retSeq = NULL;

/* Skip first lines until it starts with '>' */
for (;;)
    {
    if(fgets(lineBuf, sizeof(lineBuf), f) == NULL)
        {
        if (ferror(f))
            errnoAbort("read of fasta file failed");
        return FALSE;
        }
    lineSize = strlen(lineBuf);
    if (lineBuf[0] == '>')
        {
	if (retCommentLine != NULL)
            *retCommentLine = cloneString(lineBuf);
        offset = ftello(f);
        chopByWhite(lineBuf, words, ArraySize(words));
        name = words[0]+1;
        break;
        }
    else if (!mustStartWithComment)
        {
        if (fseeko(f, offset, SEEK_SET) < 0)
            errnoAbort("fseek on fasta file failed");
        break;
        }
    else
        offset += lineSize;
    }
/* Count up DNA. */
for (;;)
    {
    c = fgetc(f);
    if (c == EOF || c == '>')
        break;
    if (isalpha(c))
        {
        ++dnaSize;
        }
    }

if (dnaSize == 0)
    {
    warn("Invalid fasta format: sequence size == 0 for element %s",name);
    }

/* Allocate DNA and fill it up from file. */
dna = sequence = needHugeMem(dnaSize+1);
if (fseeko(f, offset, SEEK_SET) < 0)
    errnoAbort("fseek on fasta file failed");
for (;;)
    {
    c = fgetc(f);
    if (c == EOF || c == '>')
        break;
    if (isalpha(c))
        {
        /* check for non-DNA char */
        if (ntChars[c] == 0)
            {
            *dna++ = preserveCase ? 'N' : 'n';
            }
        else
            {
            *dna++ = preserveCase ? c : ntChars[c];
            }
        }
    }
if (c == '>')
    ungetc(c, f);
*dna = 0;

*retSeq = newDnaSeq(sequence, dnaSize, name);
if (ferror(f))
    errnoAbort("read of fasta file failed");    
return TRUE;
}
Exemplo n.º 19
0
// Get input from user in a controlled manner
char* get_input(FILE* stream)
{
    int i = 0;
    int size = INITIAL_BUF_SIZE;
    char* buf;

    if((buf = (char*)malloc(size)) == NULL)
    {
        perror("input.c: get_input(): initial buf malloc");
        return NULL;
    }
    buf[0] = 0;

    // Loop through input 1 char at a time
    while(1)
    {
        int c = getc(stream);

        // Increase buffer size as needed
        if((i + 1) == size) 
        { 
            size += size;

            // Double Size
            if((buf = (char*)realloc(buf, size)) == NULL)
            {
                perror("input.c: get_input(): buf realloc");
                return NULL;
            }
        }

        // \n marks the end of the input
        //  # marks the start of a comment
        //    and also the end of useful input
        if(c == '\n' || c == '#' || c == EOF)
        {
            if(c == '#')
            {
                // Burn the rest of the line
                while(c != '\n' && c != EOF)
                    c = getc(stream);
            }

            if (buf[0] == 0)
                return NULL;
            else
                break;
        }

        // Replace block of whitespace with single space
        if(isspace(c))
        {
            // Ignore leading whitespace
            if (buf[0] == 0)
                continue;

            while (isspace(c) && c != '\n' && c != '#')  
                c = getc(stream);

            ungetc(c, stream);

            if(c != '\n')
                buf[i++] = ' ';

            continue;
        }

        buf[i++] = c;
    }
    buf[i] = '\0'; // Append with null char

    return buf;
}
Exemplo n.º 20
0
LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  LoadF lf;
  int status, readstatus;
  int c;
  char fullFilename[128];
  int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */
  lf.extraline = 0;
  if (filename == NULL) {
    lua_pushliteral(L, "=stdin");
    lf.f = stdin;
  }
  else {
    // Note: Always open as the requested file, Lua should not care about
    // our crazy directory remapping.
    lua_pushfstring(L, "@%s", filename);

#if (PS3)
    // On the PS3, check always the /app_home/Lua/ directory!
    // This works both for dev-testing via remote HDD and on the game disc.
    // These work probably too just for developing, but app_home is fine!
    // /host_root/Lua/ or /dev_bdvd/PS3_GAME/USRDIR/Lua/
    CheckForValidFilenameWithPath(fullFilename, filename, "/app_home/Lua/");
#elif XBOX
    // For the Xbox we have to make sure always to load files from D:\ because
    // fopen ALWAYS expects a full paths, there are no current directories on the
    // Xbox 360 and therefore no relative paths! Check always "D:\Lua\<file>"
    CheckForValidFilenameWithPath(fullFilename, filename, "D:\\Lua\\");
#else
    // On the PC we just use the default search logic (see luaconf.h) and we
    // don't care about directories since we will already be in the correct one!
    // In earlier versions we had a lot of extra checks here.
    strcpy(fullFilename, filename);
#endif

    // Rest of this code is untouched, we just use fullFilename now!
    lf.f = fopen(fullFilename, "r");
    if (lf.f == NULL)
      return errfile(L, "open", fnameindex);
  }
  c = getc(lf.f);
  if (c == '#') {  /* Unix exec. file? */
    lf.extraline = 1;
    while ((c = getc(lf.f)) != EOF && c != '\n') ;  /* skip first line */
    if (c == '\n') c = getc(lf.f);
  }
  if (c == LUA_SIGNATURE[0] && fullFilename) {  /* binary file? */
    lf.f = freopen(fullFilename, "rb", lf.f);  /* reopen in binary mode */
    if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
    /* skip eventual `#!...' */
   while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
    lf.extraline = 0;
  }
  ungetc(c, lf.f);
  status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  readstatus = ferror(lf.f);
  if (filename) fclose(lf.f);  /* close file (even in case of errors) */
  if (readstatus) {
    lua_settop(L, fnameindex);  /* ignore results from `lua_load' */
    return errfile(L, "read", fnameindex);
  }
  lua_remove(L, fnameindex);
  return status;
}
Exemplo n.º 21
0
int
form_init(FILE *fp)
{
    char var[256];
    char val[10000];
    char *cp, *vp;
    int c;
    
    char *ep = getenv("QUERY_STRING");
    char *rm = getenv("REQUEST_METHOD");

    nvar = 0;

    if (ep && *ep && (rm && strcmp(rm, "POST") != 0))
    {
	cp = strtok(ep, "&");
	while (cp)
	{
	    vp = strchr(cp, '=');
	    if (vp)
	    {
		*vp++ = '\0';
		http_strip(vp);
	    }
	    
	    http_strip(cp);
	    form_add(cp, vp);
	    
	    cp = strtok(NULL, "&");
	}
    }
    else if (fp != NULL)
    {
	while (fscanf(fp, "%255[^=]=", var) == 1)
	{
	    val[0] = '\0';
	    
	    http_strip(var);
	    
	    c = getc(fp);
	    if (c == EOF)
	    {
		form_add(var, "");
		break;
	    }
	    
	    ungetc(c, fp);
	    if (c != '&' && fscanf(fp, "%9999[^&\n\r]", val) == 1)
	    {
		http_strip(val);
		form_add(var, val);
	    }
	    else
		form_add(var, "");
	    
	    c = getc(fp);
	    if (c != '&')
		ungetc(c, fp);
	}
    }
    
    return nvar;
}
Exemplo n.º 22
0
/*
 * y_entries:
 *	find the yacc tags and put them in.
 */
void
y_entries(void)
{
	int	c;
	char	*sp;
	bool	in_rule;
	char	tok[MAXTOKEN];

	in_rule = NO;

	while (GETC(!=, EOF))
		switch (c) {
		case '\n':
			SETLINE;
			/* FALLTHROUGH */
		case ' ':
		case '\f':
		case '\r':
		case '\t':
			break;
		case '{':
			if (skip_key('}'))
				in_rule = NO;
			break;
		case '\'':
		case '"':
			if (skip_key(c))
				in_rule = NO;
			break;
		case '%':
			if (GETC(==, '%'))
				return;
			(void)ungetc(c, inf);
			break;
		case '/':
			if (GETC(==, '*') || c == '/')
				skip_comment(c);
			else
				(void)ungetc(c, inf);
			break;
		case '|':
		case ';':
			in_rule = NO;
			break;
		default:
			if (in_rule || (!isalpha(c) && c != '.' && c != '_'))
				break;
			sp = tok;
			*sp++ = c;
			while (GETC(!=, EOF) && (intoken(c) || c == '.'))
				*sp++ = c;
			*sp = EOS;
			getline();		/* may change before ':' */
			while (iswhite(c)) {
				if (c == '\n')
					SETLINE;
				if (GETC(==, EOF))
					return;
			}
			if (c == ':') {
				pfnote(tok, lineno);
				in_rule = YES;
			}
			else
				(void)ungetc(c, inf);
		}
Exemplo n.º 23
0
stackDataT evaluateExpression(FILE *infile, Stack *S) {
    int next_char, read_ahead_char;
    int string_position = 0;
    char temp_string[MAXDIGITS];
    stackDataT data;

    while ((next_char = fgetc(infile)) != EOF) {

        // If the character is a minus, it might be an operator or it might 
        // be a negative sign
        if (next_char == MINUS) {
            // Get the next char from the stream for testing
            if ((read_ahead_char = fgetc(infile)) != EOF) {
                // Push the next char back onto the stream so it is correctly
                // processed on the next loop iteration
                if (ungetc(read_ahead_char, infile) != read_ahead_char) {
                    fprintf(stderr, "Error: Unable to parse the expression.\n");
                }
                // If the next char in the stream is a number, this minus is a
                // negative sign, add it to the number string and end this loop
                // iteration
                if (charIsANumber(read_ahead_char)) {
                    temp_string[string_position] = next_char;
                    string_position++;
                    continue;
                }
            }
        }

        // If the character is a number, add it to the temp string
        if (charIsANumber(next_char)) {
            temp_string[string_position] = next_char;
            string_position++;
        }

        // Test if the next char is whitespace between chars
        else if (charIsWhitespace(next_char)) {

            // Test if we have a number string to convert
            if (string_position > 0) {
                // Terminate the string and convert it to data
                temp_string[string_position] = '\0';
                data = atoi(temp_string);
                if (errno) {
                    // Handle number convert error
                    fprintf(
                        stderr,
                        "Error: unable to convert %s to an integer\n",
                        temp_string
                    );
                    exit(3);
                }
                // Push the data onto the stack
                push(S, data);
                // Finally, clear counter to reset temp string
                string_position = 0;
            }
        }

        // Test if the next char is an operator
        else if (charIsOperator(next_char)) {
            doSingleCalculation(S, next_char);
        }
        
        // Handle unexptected characters here
        else {
            fprintf(
                stderr, 
                "Error: the character %c is not valid.\n", 
                next_char
            );
            exit(2);
        }
    }

    // Pop the final value off the stack - that's our answer
    data = pop(S);
    
    // If there is anything left on the stack, that's an error - handle here
    if (!isEmpty(S)) {
        fprintf(
            stderr, 
            "Error: Not enough operators for the number of operands\n"
        );
        exit(4);
    }  

    return data;
}
Exemplo n.º 24
0
/* Get next line of input from G.input_file_list, flushing append buffer and
 * noting if we ran out of files without a newline on the last line we read.
 */
static char *get_next_line(char *gets_char, char *last_puts_char)
{
	char *temp = NULL;
	int len;
	char gc;

	flush_append(last_puts_char);

	/* will be returned if last line in the file
	 * doesn't end with either '\n' or '\0' */
	gc = NO_EOL_CHAR;
	for (; G.current_input_file <= G.last_input_file; G.current_input_file++) {
		FILE *fp = G.current_fp;
		if (!fp) {
			const char *path = G.input_file_list[G.current_input_file];
			fp = stdin;
			if (path != bb_msg_standard_input) {
				fp = fopen_or_warn(path, "r");
				if (!fp) {
					G.exitcode = EXIT_FAILURE;
					continue;
				}
			}
			G.current_fp = fp;
		}
		/* Read line up to a newline or NUL byte, inclusive,
		 * return malloc'ed char[]. length of the chunk read
		 * is stored in len. NULL if EOF/error */
		temp = bb_get_chunk_from_file(fp, &len);
		if (temp) {
			/* len > 0 here, it's ok to do temp[len-1] */
			char c = temp[len-1];
			if (c == '\n' || c == '\0') {
				temp[len-1] = '\0';
#if ENABLE_PLATFORM_MINGW32
				if (c == '\n' && len > 1 && temp[len-2] == '\r') {
					temp[len-2] = '\0';
				}
#endif
				gc = c;
				if (c == '\0') {
					int ch = fgetc(fp);
					if (ch != EOF)
						ungetc(ch, fp);
					else
						gc = LAST_IS_NUL;
				}
			}
			/* else we put NO_EOL_CHAR into *gets_char */
			break;

		/* NB: I had the idea of peeking next file(s) and returning
		 * NO_EOL_CHAR only if it is the *last* non-empty
		 * input file. But there is a case where this won't work:
		 * file1: "a woo\nb woo"
		 * file2: "c no\nd no"
		 * sed -ne 's/woo/bang/p' input1 input2 => "a bang\nb bang"
		 * (note: *no* newline after "b bang"!) */
		}
		/* Close this file and advance to next one */
		fclose_if_not_stdin(fp);
		G.current_fp = NULL;
	}
	*gets_char = gc;
	return temp;
}
Exemplo n.º 25
0
int
_doscan(register FILE *stream, const char *format, va_list ap)
{
	int		done = 0;	/* number of items done */
	int		nrchars = 0;	/* number of characters read */
	int		conv = 0;	/* # of conversions */
	int		base;		/* conversion base */
	unsigned long	val;		/* an integer value */
	register char	*str;		/* temporary pointer */
	char		*tmp_string;	/* ditto */
	unsigned	width = 0;	/* width of field */
	int		flags;		/* some flags */
	int		reverse;	/* reverse the checking in [...] */
	int		kind;
	register int	ic = EOF;	/* the input character */
#ifndef	NOFLOAT
	long double	ld_val;
#endif

	if (!*format) return 0;

	while (1) {
		if (isspace((int)*format)) {
			while (isspace((int)*format))
				format++;	/* skip whitespace */
			ic = getc(stream);
			nrchars++;
			while (isspace (ic)) {
				ic = getc(stream);
				nrchars++;
			}
			if (ic != EOF) ungetc(ic,stream);
			nrchars--;
		}
		if (!*format) break;	/* end of format */

		if (*format != '%') {
			ic = getc(stream);
			nrchars++;
			if (ic != *format++) break;	/* error */
			continue;
		}
		format++;
		if (*format == '%') {
			ic = getc(stream);
			nrchars++;
			if (ic == '%') {
				format++;
				continue;
			}
			else break;
		}
		flags = 0;
		if (*format == '*') {
			format++;
			flags |= FL_NOASSIGN;
		}
		if (isdigit (*format)) {
			flags |= FL_WIDTHSPEC;
			for (width = 0; isdigit (*format);)
				width = width * 10 + *format++ - '0';
		}

		switch (*format) {
		case 'h': flags |= FL_SHORT; format++; break;
		case 'l': flags |= FL_LONG; format++; break;
		case 'L': flags |= FL_LONGDOUBLE; format++; break;
		}
		kind = *format;
		if ((kind != 'c') && (kind != '[') && (kind != 'n')) {
			do {
				ic = getc(stream);
				nrchars++;
			} while (isspace(ic));
			if (ic == EOF) break;		/* outer while */
		} else if (kind != 'n') {		/* %c or %[ */
			ic = getc(stream);
			if (ic == EOF) break;		/* outer while */
			nrchars++;
		}
		switch (kind) {
		default:
			/* not recognized, like %q */
			return conv || (ic != EOF) ? done : EOF;
			break;
		case 'n':
			if (!(flags & FL_NOASSIGN)) {	/* silly, though */
				if (flags & FL_SHORT)
					*va_arg(ap, short *) = (short) nrchars;
				else if (flags & FL_LONG)
					*va_arg(ap, long *) = (long) nrchars;
				else
					*va_arg(ap, int *) = (int) nrchars;
			}
			break;
		case 'p':		/* pointer */
			set_pointer(flags);
			/* fallthrough */
		case 'b':		/* binary */
		case 'd':		/* decimal */
		case 'i':		/* general integer */
		case 'o':		/* octal */
		case 'u':		/* unsigned */
		case 'x':		/* hexadecimal */
		case 'X':		/* ditto */
			if (!(flags & FL_WIDTHSPEC) || width > NUMLEN)
				width = NUMLEN;
			if (!width) return done;

			str = o_collect(ic, stream, kind, width, &base);
			if (str < inp_buf
			    || (str == inp_buf
				    && (*str == '-'
					|| *str == '+'))) return done;

			/*
			 * Although the length of the number is str-inp_buf+1
			 * we don't add the 1 since we counted it already
			 */
			nrchars += str - inp_buf;

			if (!(flags & FL_NOASSIGN)) {
				if (kind == 'd' || kind == 'i')
				    val = strtol(inp_buf, &tmp_string, base);
				else
				    val = strtoul(inp_buf, &tmp_string, base);
				if (flags & FL_LONG)
					*va_arg(ap, unsigned long *) = (unsigned long) val;
				else if (flags & FL_SHORT)
					*va_arg(ap, unsigned short *) = (unsigned short) val;
				else
					*va_arg(ap, unsigned *) = (unsigned) val;
			}
			break;
		case 'c':
			if (!(flags & FL_WIDTHSPEC))
				width = 1;
			if (!(flags & FL_NOASSIGN))
				str = va_arg(ap, char *);
			if (!width) return done;

			while (width && ic != EOF) {
				if (!(flags & FL_NOASSIGN))
					*str++ = (char) ic;
				if (--width) {
					ic = getc(stream);
					nrchars++;
				}
			}

			if (width) {
				if (ic != EOF) ungetc(ic,stream);
				nrchars--;
			}
			break;
		case 's':
			if (!(flags & FL_WIDTHSPEC))
				width = 0xffff;
			if (!(flags & FL_NOASSIGN))
				str = va_arg(ap, char *);
			if (!width) return done;

			while (width && ic != EOF && !isspace(ic)) {
				if (!(flags & FL_NOASSIGN))
					*str++ = (char) ic;
				if (--width) {
					ic = getc(stream);
					nrchars++;
				}
			}
			/* terminate the string */
			if (!(flags & FL_NOASSIGN))
				*str = '\0';	
			if (width) {
				if (ic != EOF) ungetc(ic,stream);
				nrchars--;
			}
			break;
		case '[':
			if (!(flags & FL_WIDTHSPEC))
				width = 0xffff;
			if (!width) return done;

			if ( *++format == '^' ) {
				reverse = 1;
				format++;
			} else
				reverse = 0;

			for (str = Xtable; str < &Xtable[NR_CHARS]
							; str++)
				*str = 0;

			if (*format == ']') Xtable[(int)*format++] = 1;

			while (*format && *format != ']') {
				Xtable[(int)*format++] = 1;
				if (*format == '-') {
					format++;
					if (*format
					    && *format != ']'
					    && *(format) >= *(format -2)) {
						int c;

						for( c = *(format -2) + 1
						    ; c <= *format ; c++)
							Xtable[c] = 1;
						format++;
					}
					else Xtable['-'] = 1;
				}
			}
			if (!*format) return done;
			
			if (!(Xtable[ic] ^ reverse)) {
			/* MAT 8/9/96 no match must return character */
				ungetc(ic, stream);
				return done;
			}

			if (!(flags & FL_NOASSIGN))
				str = va_arg(ap, char *);

			do {
				if (!(flags & FL_NOASSIGN))
					*str++ = (char) ic;
				if (--width) {
					ic = getc(stream);
					nrchars++;
				}
			} while (width && ic != EOF && (Xtable[ic] ^ reverse));

			if (width) {
				if (ic != EOF) ungetc(ic, stream);
				nrchars--;
			}
			if (!(flags & FL_NOASSIGN)) {	/* terminate string */
				*str = '\0';	
			}
			break;
		}		/* end switch */
		conv++;
		if (!(flags & FL_NOASSIGN) && kind != 'n') done++;
		format++;
	}
	return conv || (ic != EOF) ? done : EOF;
}
Exemplo n.º 26
0
static boolean addElementLen (FILE *fp, tree *tr, nodeptr p, boolean readBranchLengths, boolean readNodeLabels, int *lcount)
{   
  nodeptr  q;
  int      n, ch, fres;
  
  if ((ch = treeGetCh(fp)) == '(') 
    { 
      n = (tr->nextnode)++;
      if (n > 2*(tr->mxtips) - 2) 
	{
	  if (tr->rooted || n > 2*(tr->mxtips) - 1) 
	    {
	      printf("ERROR: Too many internal nodes.  Is tree rooted?\n");
	      printf("       Deepest splitting should be a trifurcation.\n");
	      return FALSE;
	    }
	  else 
	    {
	      assert(!readNodeLabels);
	      tr->rooted = TRUE;
	    }
	}
      
      q = tr->nodep[n];

      if (! addElementLen(fp, tr, q->next, readBranchLengths, readNodeLabels, lcount))        return FALSE;
      if (! treeNeedCh(fp, ',', "in"))             return FALSE;
      if (! addElementLen(fp, tr, q->next->next, readBranchLengths, readNodeLabels, lcount))  return FALSE;
      if (! treeNeedCh(fp, ')', "in"))             return FALSE;
      
      if(readNodeLabels)
	{
	  char label[64];
	  int support;

	  if(treeGetLabel (fp, label, 10))
	    {	
	      int val = sscanf(label, "%d", &support);
      
	      assert(val == 1);

	      /*printf("LABEL %s Number %d\n", label, support);*/
	      /*p->support = q->support = support;*/
	      /*printf("%d %d %d %d\n", p->support, q->support, p->number, q->number);*/
	      assert(p->number > tr->mxtips && q->number > tr->mxtips);
	      *lcount = *lcount + 1;
	    }
	}
      else	
	(void) treeFlushLabel(fp);
    }
  else 
    {   
      ungetc(ch, fp);
      if ((n = treeFindTipName(fp, tr)) <= 0)          return FALSE;
      q = tr->nodep[n];
      if (tr->start->number > n)  tr->start = q;
      (tr->ntips)++;
    }
  
  if(readBranchLengths)
    {
      double branch;
      if (! treeNeedCh(fp, ':', "in"))                 return FALSE;
      if (! treeProcessLength(fp, &branch))            return FALSE;
      
      /*printf("Branch %8.20f %d\n", branch, tr->numBranches);*/
      hookup(p, q, &branch, tr->numBranches);
    }
  else
    {
      fres = treeFlushLen(fp);
      if(!fres) return FALSE;
      
      hookupDefault(p, q, tr->numBranches);
    }
  return TRUE;          
} 
Exemplo n.º 27
0
static int
read_disabled_heur_dissector_list_file(const char *ff_path, FILE *ff,
                               GList **flp)
{
  heur_protocol_def *heur;
  int         c;
  char       *heuristic_name;
  int         heuristic_name_len;
  int         name_index;
  gboolean    parse_enabled;
  gboolean    enabled;
  int         line = 1;


  /* Allocate the protocol name buffer. */
  heuristic_name_len = INIT_BUF_SIZE;
  heuristic_name = (char *)g_malloc(heuristic_name_len + 1);

  for (line = 1; ; line++) {
    /* Lines in a disabled protocol file contain the "filter name" of
       a protocol to be disabled. */

    /* Skip over leading white space, if any. */
    while ((c = getc(ff)) != EOF && g_ascii_isspace(c)) {
      if (c == '\n') {
        /* Blank line. */
        continue;
      }
    }

    if (c == EOF) {
      if (ferror(ff))
        goto error;     /* I/O error */
      else
        break;  /* Nothing more to read */
    }
    ungetc(c, ff);      /* Unread the non-white-space character. */

    /* Get the name of the protocol. */
    name_index = 0;
    enabled = FALSE;
    parse_enabled = FALSE;
    for (;;) {
      c = getc(ff);
      if (c == EOF)
        break;  /* End of file, or I/O error */
      if (g_ascii_isspace(c))
        break;  /* Trailing white space, or end of line. */
      if (c == ',') {/* Separator for enable/disable */
        parse_enabled = TRUE;
        continue;
      }
      if (c == '#')
        break;  /* Start of comment, running to end of line. */
      if (parse_enabled) {
          enabled = ((c == '1') ? TRUE : FALSE);
          break;
      }
      /* Add this character to the protocol name string. */
      if (name_index >= heuristic_name_len) {
        /* protocol name buffer isn't long enough; double its length. */
        heuristic_name_len *= 2;
        heuristic_name = (char *)g_realloc(heuristic_name, heuristic_name_len + 1);
      }
      heuristic_name[name_index] = c;
      name_index++;
    }

    if (g_ascii_isspace(c) && c != '\n') {
      /* Skip over trailing white space. */
      while ((c = getc(ff)) != EOF && c != '\n' && g_ascii_isspace(c))
        ;
      if (c != EOF && c != '\n' && c != '#') {
        /* Non-white-space after the protocol name; warn about it,
           in case we come up with a reason to use it. */
        g_warning("'%s' line %d has extra stuff after the protocol name.",
                  ff_path, line);
      }
    }
    if (c != EOF && c != '\n') {
      /* Skip to end of line. */
      while ((c = getc(ff)) != EOF && c != '\n')
        ;
    }

    if (c == EOF) {
      if (ferror(ff))
        goto error;     /* I/O error */
      else {
        /* EOF, not error; no newline seen before EOF */
        g_warning("'%s' line %d doesn't have a newline.", ff_path,
                  line);
      }
      break;    /* nothing more to read */
    }

    /* Null-terminate the protocol name. */
    if (name_index >= heuristic_name_len) {
      /* protocol name buffer isn't long enough; double its length. */
      heuristic_name_len *= 2;
      heuristic_name = (char *)g_realloc(heuristic_name, heuristic_name_len + 1);
    }
    heuristic_name[name_index] = '\0';

    /* Add the new protocol to the list of disabled protocols */
    heur         = (heur_protocol_def *) g_malloc(sizeof(heur_protocol_def));
    heur->name   = g_strdup(heuristic_name);
    heur->enabled = enabled;
    *flp = g_list_append(*flp, heur);
  }
  g_free(heuristic_name);
  return 0;

error:
  g_free(heuristic_name);
  return errno;
}
Exemplo n.º 28
0
int treeReadLen (FILE *fp, tree *tr, boolean readBranches, boolean readNodeLabels, boolean topologyOnly)
{
  nodeptr  
    p;
  
  int      
    i, 
    ch, 
    lcount = 0; 

  for (i = 1; i <= tr->mxtips; i++) 
    {
      tr->nodep[i]->back = (node *) NULL; 
      /*if(topologyOnly)
	tr->nodep[i]->support = -1;*/
    }

  for(i = tr->mxtips + 1; i < 2 * tr->mxtips; i++)
    {
      tr->nodep[i]->back = (nodeptr)NULL;
      tr->nodep[i]->next->back = (nodeptr)NULL;
      tr->nodep[i]->next->next->back = (nodeptr)NULL;
      tr->nodep[i]->number = i;
      tr->nodep[i]->next->number = i;
      tr->nodep[i]->next->next->number = i;

      /*if(topologyOnly)
	{
	  tr->nodep[i]->support = -2;
	  tr->nodep[i]->next->support = -2;
	  tr->nodep[i]->next->next->support = -2;
	  }*/
    }

  if(topologyOnly)
    tr->start       = tr->nodep[tr->mxtips];
  else
    tr->start       = tr->nodep[1];

  tr->ntips       = 0;
  tr->nextnode    = tr->mxtips + 1;      
 
  for(i = 0; i < tr->numBranches; i++)
    tr->partitionSmoothed[i] = FALSE;
  
  tr->rooted      = FALSE;     

  p = tr->nodep[(tr->nextnode)++]; 
  
  while((ch = treeGetCh(fp)) != '(');
      
  if(!topologyOnly)
    assert(readBranches == FALSE && readNodeLabels == FALSE);
  
       
  if (! addElementLen(fp, tr, p, readBranches, readNodeLabels, &lcount))                 
    assert(0);
  if (! treeNeedCh(fp, ',', "in"))                
    assert(0);
  if (! addElementLen(fp, tr, p->next, readBranches, readNodeLabels, &lcount))
    assert(0);
  if (! tr->rooted) 
    {
      if ((ch = treeGetCh(fp)) == ',') 
	{ 
	  if (! addElementLen(fp, tr, p->next->next, readBranches, readNodeLabels, &lcount))
	    assert(0);	    
	}
      else 
	{                                    /*  A rooted format */
	  tr->rooted = TRUE;
	  if (ch != EOF)  (void) ungetc(ch, fp);
	}	
    }
  else 
    {      
      p->next->next->back = (nodeptr) NULL;
    }
  if (! treeNeedCh(fp, ')', "in"))                
    assert(0);

  if(topologyOnly)
    assert(!(tr->rooted && readNodeLabels));

  (void) treeFlushLabel(fp);
  
  if (! treeFlushLen(fp))                         
    assert(0);
 
  if (! treeNeedCh(fp, ';', "at end of"))       
    assert(0);
  
  if (tr->rooted) 
    {     
      assert(!readNodeLabels);

      p->next->next->back = (nodeptr) NULL;      
      tr->start = uprootTree(tr, p->next->next, FALSE, FALSE);      
      if (! tr->start)                              
	{
	  printf("FATAL ERROR UPROOTING TREE\n");
	  assert(0);
	}    
    }
  else    
    tr->start = findAnyTip(p, tr->mxtips);    
  
  
 
  assert(tr->ntips == tr->mxtips);
  
 
   
  
  return lcount;
}
Exemplo n.º 29
0
/*
 * return end of string - WARNING: malloc!
 */
int
xpmGetString(xpmData *mdata, char **sptr, unsigned int *l)
{
    unsigned int i, n = 0;
    int c;
    char *p, *q, buf[BUFSIZ];

    if (!mdata->type || mdata->type == XPMBUFFER) {
	if (mdata->cptr) {
	    char *start;

	    while (isspace(c = *mdata->cptr) && c != mdata->Eos)
		mdata->cptr++;
	    start = mdata->cptr;
	    while ((c = *mdata->cptr) && c != mdata->Eos)
		mdata->cptr++;
	    n = mdata->cptr - start + 1;
	    p = (char *) XpmMalloc(n);
	    if (!p)
		return (XpmNoMemory);
	    strncpy(p, start, n);
	    if (mdata->type)		/* XPMBUFFER */
		p[n - 1] = '\0';
	}
    } else {
	FILE *file = mdata->stream.file;

	while ((c = getc(file)) != EOF && isspace(c) && c != mdata->Eos);
	if (c == EOF)
	    return (XpmFileInvalid);
	p = NULL;
	i = 0;
	q = buf;
	p = (char *) XpmMalloc(1);
	while (c != mdata->Eos && c != EOF) {
	    if (i == BUFSIZ) {
		/* get to the end of the buffer */
		/* malloc needed memory */
		q = (char *) XpmRealloc(p, n + i);
		if (!q) {
		    XpmFree(p);
		    return (XpmNoMemory);
		}
		p = q;
		q += n;
		/* and copy what we already have */
		strncpy(q, buf, i);
		n += i;
		i = 0;
		q = buf;
	    }
	    *q++ = c;
	    i++;
	    c = getc(file);
	}
	if (c == EOF) {
	    XpmFree(p);
	    return (XpmFileInvalid);
	}
	if (n + i != 0) {
	    /* malloc needed memory */
	    q = (char *) XpmRealloc(p, n + i + 1);
	    if (!q) {
		XpmFree(p);
		return (XpmNoMemory);
	    }
	    p = q;
	    q += n;
	    /* and copy the buffer */
	    strncpy(q, buf, i);
	    n += i;
	    p[n++] = '\0';
	} else {
	    *p = '\0';
	    n = 1;
	}
	ungetc(c, file);
    }
    *sptr = p;
    *l = n;
    return (XpmSuccess);
}
char peek (FILE * f)
{
    char c = fgetc (f);
    ungetc (c, f);
    return c;
}