boolean_t
PLCache_read(PLCache_t * cache, const char * filename)
{
    FILE *	file = NULL;
    int		line_number = 0;
    char	line[1024];
    ni_proplist	pl;
    enum { 
	nowhere_e,
	start_e, 
	body_e, 
	end_e 
    }		where = nowhere_e;

    NI_INIT(&pl);
    file = fopen(filename, "r");
    if (file == NULL) {
	perror(filename);
	goto failed;
    }

    while (1) {
	if (my_fgets(line, sizeof(line), file) != line) {
	    if (where == start_e || where == body_e) {
		fprintf(stderr, "file ends prematurely\n");
	    }
	    break;
	}
	line_number++;
	if (strcmp(line, "{\n") == 0) {
	    if (where != end_e && where != nowhere_e) {
		fprintf(stderr, "unexpected '{' at line %d\n", 
			line_number);
		goto failed;
	    }
	    where = start_e;
	}
	else if (strcmp(line, "}\n") == 0) {
	    if (where != start_e && where != body_e) {
		fprintf(stderr, "unexpected '}' at line %d\n", 
			line_number);
		goto failed;
	    }
	    if (pl.nipl_len > 0) {
		PLCache_append(cache, PLCacheEntry_create(pl));
		ni_proplist_free(&pl);
	    }
	    where = end_e;
	}
	else {
	    char	propname[128];
	    char	propval[768] = "";
	    int 	len = strlen(line);
	    char *	sep = strchr(line, '=');
	    int 	whitespace_len = strspn(line, " \t\n");

	    if (whitespace_len == len) {
		continue;
	    }
	    if (sep) {
		int nlen = (sep - line) - whitespace_len;
		int vlen = len - whitespace_len - nlen - 2;

		if (nlen >= sizeof(propname)) {
		    fprintf(stderr,
			    "property name truncated to %d bytes at line %d\n",
			    (int)sizeof(propname) - 1,
			    line_number);
		    nlen = sizeof(propname) - 1;
		}
		if (vlen >= sizeof(propval)) {
		    fprintf(stderr, 
			    "value truncated to %d bytes at line %d\n",
			    (int)sizeof(propval) - 1,
			    line_number);
		    vlen = sizeof(propval) - 1;
		}
		strncpy(propname, line + whitespace_len, nlen);
		propname[nlen] = '\0';
		strncpy(propval, sep + 1, vlen);
		propval[vlen] = '\0';
		ni_proplist_insertprop(&pl, propname, propval, NI_INDEX_NULL);
	    }
	    else {
		int nlen = len - whitespace_len - 1;

		if (nlen >= sizeof(propname)) {
		    fprintf(stderr,
			    "property name truncated to %d bytes at line %d\n",
			    (int)sizeof(propname) - 1,
			    line_number);
		    nlen = sizeof(propname) - 1;
		}
		strncpy(propname, line + whitespace_len, nlen);
		propname[nlen] = '\0';
		ni_proplist_insertprop(&pl, propname, NULL, NI_INDEX_NULL);
	    }
	    where = body_e;
	}
    }

 failed:
    if (file)
	fclose(file);
    ni_proplist_free(&pl);
    return (TRUE);
}
Beispiel #2
0
void p_http_connect(struct url *u) {
  struct http_data *hd;
  char *p;
  struct in_addr saddr;

  /* Create our http_data */
  hd = malloc(sizeof(struct http_data));
  memset(hd,0,sizeof(struct http_data));
  u->extra = hd;

  /* HTTP defaults */
  if (!u->port)
    u->port = 80;
  if (!u->path)
    u->path = strdup("/");

  /* First try it as aaa.bbb.ccc.ddd. */
  saddr.s_addr = inet_addr(u->server);
  if (saddr.s_addr == -1) {

    /* Resolve hostname */
    url_setstatus(u,URL_STATUS_RESOLVING);
    hd->he = gethostbyname(u->server);
    if (!hd->he) {
      browserwin_errormsg(u->browser,"The web server could not be found<br>(DNS error)");
      url_setstatus(u,URL_STATUS_ERROR);
      return;
    }    
  }
    
  /* Create TCP socket */
  hd->fd = socket(AF_INET, SOCK_STREAM, 0);
  if (!hd->fd) {
    browserwin_errormsg(u->browser,
			"Can't create TCP/IP socket. Has TCP/IP"
			" networking been compiled into the kernel?");
    url_setstatus(u,URL_STATUS_ERROR);
    return;
  }    

  /* Connect socket */
  url_setstatus(u,URL_STATUS_CONNECTING);
  memset(&hd->server_addr,0,sizeof(hd->server_addr));
  hd->server_addr.sin_family = AF_INET;
  hd->server_addr.sin_port = htons(u->port);

  if (saddr.s_addr == -1) {
    hd->server_addr.sin_addr = *((struct in_addr *)hd->he->h_addr);
  } else {
    hd->server_addr.sin_addr.s_addr = saddr.s_addr;
  }

  if (connect(hd->fd, (struct sockaddr *)&hd->server_addr, sizeof(struct sockaddr)) == -1) {
    browserwin_errormsg(u->browser,
			"Can't connect to the web server. "
			"The server could be down or not accepting connections.");
    url_setstatus(u,URL_STATUS_ERROR);
    return;
  }    
  hd->out = fdopen(hd->fd,"w");

  /* Send HTTP headers */\
  url_setstatus(u,URL_STATUS_WRITE);
  fprintf(hd->out,
	  "GET %s HTTP/1.0\r\n"
	  "User-Agent: %s\r\n"
	  "\r\n",
	  u->path,
	  USER_AGENT);
  fflush(hd->out);

  /* Receive HTTP headers with buffered I/O */
  url_setstatus(u,URL_STATUS_READ);
  hd->headerline = malloc(HEADER_LINE_BUFFER);
  if (!hd->headerline) {
      browserwin_errormsg(u->browser, "The HTTP headers are incomplete");
      url_setstatus(u,URL_STATUS_ERROR);
      return;
  }

  for (;;) {
    /* Get one header line */
    if (!my_fgets(hd->headerline, HEADER_LINE_BUFFER, hd->fd)) {
      browserwin_errormsg(u->browser, "The HTTP headers are incomplete");
      url_setstatus(u,URL_STATUS_ERROR);
      return;
    }

    /* The fgets separates lines with \n, but there might be a stray \r
     * at the end since most web servers send \r\n
     */
    if (p = strchr(hd->headerline,'\r'))
      *p = 0;
    if (p = strchr(hd->headerline,'\n'))
      *p = 0;
    
    /* Separate into name and value */
    p = strchr(hd->headerline,':');
    if (p) {
      *p = 0;
      p++;
      /* There should be a space after the colon, if so chop if off */
      if (*p == ' ')
	p++;
    }
    else 
      p = "";

    if (!*hd->headerline)
      break;

    p_http_header(u,hd->headerline,p);
  };
  free(hd->headerline);
  hd->headerline = NULL;

  /* Allocate our initial buffer. If we didn't get a content-size header,
   * use a hardcoded default size.
   */
  if (u->size)
    hd->buffer_size = u->size;
  else
    hd->buffer_size = DEFAULT_PAGE_BUFFER;
  hd->buffer = malloc(hd->buffer_size);
  if (!hd->buffer) {
    browserwin_errormsg(u->browser, "Unable to allocate memory to hold the web page");
    url_setstatus(u,URL_STATUS_ERROR);
    return;
  }    
  DBG("malloc'ed %d bytes for page buffer\n", hd->buffer_size);

  /* Yay, start reading the page's content asynchronously */
  url_activate(u);
}
Beispiel #3
0
int main(int argc, char *argv[])
{
  FILE *fout, *fasm, *fhdr = NULL, *frlist;
  const struct parsed_proto *pp;
  int no_decorations = 0;
  char comment_char = '#';
  char words[20][256];
  char word[256];
  char line[256];
  char last_sym[32];
  unsigned long val;
  unsigned long cnt;
  const char *sym;
  enum dx_type type;
  char **pub_syms;
  int pub_sym_cnt = 0;
  int pub_sym_alloc;
  char **rlist;
  int rlist_cnt = 0;
  int rlist_alloc;
  int header_mode = 0;
  int is_ro = 0;
  int is_label;
  int is_bss;
  int wordc;
  int first;
  int arg_out;
  int arg = 1;
  int len;
  int w, i;
  char *p;
  char *p2;

  if (argc < 4) {
    // -nd: no symbol decorations
    printf("usage:\n%s [-nd] [-i] [-a] <.s> <.asm> <hdrf> [rlist]*\n"
           "%s -hdr <.h> <.asm>\n",
      argv[0], argv[0]);
    return 1;
  }

  for (arg = 1; arg < argc; arg++) {
    if (IS(argv[arg], "-nd"))
      no_decorations = 1;
    else if (IS(argv[arg], "-i"))
      g_cconv_novalidate = 1;
    else if (IS(argv[arg], "-a")) {
      comment_char = '@';
      g_arm_mode = 1;
    }
    else if (IS(argv[arg], "-hdr"))
      header_mode = 1;
    else
      break;
  }

  arg_out = arg++;

  asmfn = argv[arg++];
  fasm = fopen(asmfn, "r");
  my_assert_not(fasm, NULL);

  if (!header_mode) {
    hdrfn = argv[arg++];
    fhdr = fopen(hdrfn, "r");
    my_assert_not(fhdr, NULL);
  }

  fout = fopen(argv[arg_out], "w");
  my_assert_not(fout, NULL);

  pub_sym_alloc = 64;
  pub_syms = malloc(pub_sym_alloc * sizeof(pub_syms[0]));
  my_assert_not(pub_syms, NULL);

  rlist_alloc = 64;
  rlist = malloc(rlist_alloc * sizeof(rlist[0]));
  my_assert_not(rlist, NULL);

  for (; arg < argc; arg++) {
    frlist = fopen(argv[arg], "r");
    my_assert_not(frlist, NULL);

    while (my_fgets(line, sizeof(line), frlist)) {
      p = sskip(line);
      if (*p == 0 || *p == ';')
        continue;

      p = next_word(words[0], sizeof(words[0]), p);
      if (words[0][0] == 0)
        continue;

      if (rlist_cnt >= rlist_alloc) {
        rlist_alloc = rlist_alloc * 2 + 64;
        rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
        my_assert_not(rlist, NULL);
      }
      rlist[rlist_cnt++] = strdup(words[0]);
    }

    fclose(frlist);
    frlist = NULL;
  }

  if (rlist_cnt > 0)
    qsort(rlist, rlist_cnt, sizeof(rlist[0]), cmpstringp);

  qsort(unwanted_syms, ARRAY_SIZE(unwanted_syms),
    sizeof(unwanted_syms[0]), cmpstringp);

  last_sym[0] = 0;

  while (1) {
    next_section(fasm, line);
    if (feof(fasm))
      break;
    if (IS(line + 1, "text"))
      continue;

    if (IS(line + 1, "rdata")) {
      is_ro = 1;
      if (!header_mode)
        fprintf(fout, "\n.section .rodata\n");
    }
    else if (IS(line + 1, "data")) {
      is_ro = 0;
      if (!header_mode)
        fprintf(fout, "\n.data\n");
    }
    else
      aerr("unhandled section: '%s'\n", line);

    if (!header_mode)
      fprintf(fout, ".align %d\n", align_value(4));

    while (my_fgets(line, sizeof(line), fasm))
    {
      sym = NULL;
      asmln++;

      p = sskip(line);
      if (*p == 0)
        continue;

      if (*p == ';') {
        if (IS_START(p, ";org") && sscanf(p + 5, "%Xh", &i) == 1) {
          // ;org is only seen at section start, so assume . addr 0
          i &= 0xfff;
          if (i != 0 && !header_mode)
            fprintf(fout, "\t\t  .skip 0x%x\n", i);
        }
        continue;
      }

      for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
        p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
        if (*p == 0 || *p == ';') {
          wordc++;
          break;
        }
        if (*p == ',') {
          p = sskip(p + 1);
        }
      }

      if (*p == ';') {
        p = sskip(p + 1);
        if (IS_START(p, "sctclrtype"))
          g_func_sym_pp = NULL;
      }

      if (wordc == 2 && IS(words[1], "ends"))
        break;
      if (wordc <= 2 && IS(words[0], "end"))
        break;
      if (wordc < 2)
        aerr("unhandled: '%s'\n", words[0]);

      // don't cares
      if (IS(words[0], "assume"))
        continue;

      if (IS(words[0], "align")) {
        if (header_mode)
          continue;

        val = parse_number(words[1]);
        fprintf(fout, "\t\t  .align %d", align_value(val));
        goto fin;
      }

      w = 1;
      type = parse_dx_directive(words[0]);
      if (type == DXT_UNSPEC) {
        type = parse_dx_directive(words[1]);
        sym = words[0];
        w = 2;
      }
      if (type == DXT_UNSPEC)
        aerr("unhandled decl: '%s %s'\n", words[0], words[1]);

      if (sym != NULL)
      {
        if (header_mode) {
          int is_str = 0;

          fprintf(fout, "extern ");
          if (is_ro)
            fprintf(fout, "const ");

          switch (type) {
          case DXT_BYTE:
            for (i = w; i < wordc; i++)
              if (words[i][0] == '\'')
                is_str = 1;
            if (is_str)
              fprintf(fout, "char     %s[];\n", sym);
            else
              fprintf(fout, "uint8_t  %s;\n", sym);
            break;

          case DXT_WORD:
            fprintf(fout, "uint16_t %s;\n", sym);
            break;

          case DXT_DWORD:
            fprintf(fout, "uint32_t %s;\n", sym);
            break;

          default:
            fprintf(fout, "_UNKNOWN %s;\n", sym);
            break;
          }

          continue;
        }

        snprintf(last_sym, sizeof(last_sym), "%s", sym);

        pp = proto_parse(fhdr, sym, 1);
        if (pp != NULL) {
          g_func_sym_pp = NULL;

          // public/global name
          if (pub_sym_cnt >= pub_sym_alloc) {
            pub_sym_alloc *= 2;
            pub_syms = realloc(pub_syms, pub_sym_alloc * sizeof(pub_syms[0]));
            my_assert_not(pub_syms, NULL);
          }
          pub_syms[pub_sym_cnt++] = strdup(sym);
        }

        len = strlen(sym);
        fprintf(fout, "%s%s:", no_decorations ? "" : "_", sym);

        len += 2;
        if (len < 8)
          fprintf(fout, "\t");
        if (len < 16)
          fprintf(fout, "\t");
        if (len <= 16)
          fprintf(fout, "  ");
        else
          fprintf(fout, " ");
      }
      else {
        if (header_mode)
          continue;

        fprintf(fout, "\t\t  ");
      }

      // fill out some unwanted strings with zeroes..
      if (type == DXT_BYTE && words[w][0] == '\''
        && is_unwanted_sym(last_sym))
      {
        len = 0;
        for (; w < wordc; w++) {
          if (words[w][0] == '\'') {
            p = words[w] + 1;
            for (; *p && *p != '\''; p++)
              len++;
          }
          else {
            // assume encoded byte
            len++;
          }
        }
        fprintf(fout, ".skip %d", len);
        goto fin;
      }
      else if (type == DXT_BYTE
        && (words[w][0] == '\''
            || (w + 1 < wordc && words[w + 1][0] == '\'')))
      {
        // string; use asciz for most common case
        if (w == wordc - 2 && IS(words[w + 1], "0")) {
          fprintf(fout, ".asciz \"");
          wordc--;
        }
        else
          fprintf(fout, ".ascii \"");

        for (; w < wordc; w++) {
          if (words[w][0] == '\'') {
            p = words[w] + 1;
            p2 = strchr(p, '\'');
            if (p2 == NULL)
              aerr("unterminated string? '%s'\n", p);
            memcpy(word, p, p2 - p);
            word[p2 - p] = 0;
            fprintf(fout, "%s", escape_string(word));
          }
          else {
            val = parse_number(words[w]);
            if (val & ~0xff)
              aerr("bad string trailing byte?\n");
            // unfortunately \xHH is unusable - gas interprets
            // things like \x27b as 0x7b, so have to use octal here
            fprintf(fout, "\\%03lo", val);
          }
        }
        fprintf(fout, "\"");
        goto fin;
      }

      if (w == wordc - 2) {
        if (IS_START(words[w + 1], "dup(")) {
          cnt = parse_number(words[w]);
          p = words[w + 1] + 4;
          p2 = strchr(p, ')');
          if (p2 == NULL)
            aerr("bad dup?\n");
          memmove(word, p, p2 - p);
          word[p2 - p] = 0;

          val = 0;
          if (!IS(word, "?"))
            val = parse_number(word);

          fprintf(fout, ".fill 0x%02lx,%d,0x%02lx",
            cnt, type_size(type), val);
          goto fin;
        }
      }

      if (type == DXT_DWORD && words[w][0] == '\''
        && words[w][5] == '\'' && strlen(words[w]) == 6)
      {
        if (w != wordc - 1)
          aerr("TODO\n");

        p = words[w];
        val = (p[1] << 24) | (p[2] << 16) | (p[3] << 8) | p[4];
        fprintf(fout, ".long 0x%lx", val);
        snprintf(g_comment, sizeof(g_comment), "%s", words[w]);
        goto fin;
      }

      if (type >= DXT_DWORD && strchr(words[w], '.'))
      {
        if (w != wordc - 1)
          aerr("TODO\n");

        if (g_arm_mode && type == DXT_TEN) {
          fprintf(fout, ".fill 10");
          snprintf(g_comment, sizeof(g_comment), "%s %s",
            type_name_float(type), words[w]);
        }
        else
          fprintf(fout, "%s %s", type_name_float(type), words[w]);
        goto fin;
      }

      first = 1;
      fprintf(fout, "%s ", type_name(type));
      for (; w < wordc; w++)
      {
        if (!first)
          fprintf(fout, ", ");

        is_label = is_bss = 0;
        if (w <= wordc - 2 && IS(words[w], "offset")) {
          is_label = 1;
          w++;
        }
        else if (IS(words[w], "?")) {
          is_bss = 1;
        }
        else if (type == DXT_DWORD
                 && !('0' <= words[w][0] && words[w][0] <= '9'))
        {
          // assume label
          is_label = 1;
        }

        if (is_bss) {
          fprintf(fout, "0");
        }
        else if (is_label) {
          p = words[w];
          if (IS_START(p, "loc_") || IS_START(p, "__imp")
             || strchr(p, '?') || strchr(p, '@')
             || bsearch(&p, rlist, rlist_cnt, sizeof(rlist[0]),
                  cmpstringp))
          {
            fprintf(fout, "0");
            snprintf(g_comment, sizeof(g_comment), "%s", p);
          }
          else {
            pp = check_var(fhdr, sym, p);
            if (pp == NULL) {
              fprintf(fout, "%s%s",
                (no_decorations || p[0] == '_') ? "" : "_", p);
            }
            else {
              if (no_decorations)
                fprintf(fout, "%s", pp->name);
              else
                output_decorated_pp(fout, pp);
            }
          }
        }
        else {
          val = parse_number(words[w]);
          if (val < 10)
            fprintf(fout, "%ld", val);
          else
            fprintf(fout, "0x%lx", val);
        }

        first = 0;
      }

fin:
      if (g_comment[0] != 0) {
        fprintf(fout, "\t\t%c %s", comment_char, g_comment);
        g_comment[0] = 0;
      }
      fprintf(fout, "\n");
    }
  }

  fprintf(fout, "\n");

  // dump public syms
  for (i = 0; i < pub_sym_cnt; i++)
    fprintf(fout, ".global %s%s\n",
      no_decorations ? "" : "_", pub_syms[i]);

  fclose(fout);
  fclose(fasm);
  if (fhdr != NULL)
    fclose(fhdr);

  return 0;
}
Beispiel #4
0
static int32
GetChar(JSTokenStream *ts)
{
    int32 c;
    ptrdiff_t i, j, len, olen;
    JSBool crflag;
    char cbuf[JS_LINE_LIMIT];
    jschar *ubuf, *nl;

    if (ts->ungetpos != 0) {
        c = ts->ungetbuf[--ts->ungetpos];
    } else {
        do {
            if (ts->linebuf.ptr == ts->linebuf.limit) {
                len = PTRDIFF(ts->userbuf.limit, ts->userbuf.ptr, jschar);
                if (len <= 0) {
                    if (!ts->file) {
                        ts->flags |= TSF_EOF;
                        return EOF;
                    }

                    /* Fill ts->userbuf so that \r and \r\n convert to \n. */
                    crflag = (ts->flags & TSF_CRFLAG) != 0;
                    len = my_fgets(cbuf, JS_LINE_LIMIT - crflag, ts->file);
                    if (len <= 0) {
                        ts->flags |= TSF_EOF;
                        return EOF;
                    }
                    olen = len;
                    ubuf = ts->userbuf.base;
                    i = 0;
                    if (crflag) {
                        ts->flags &= ~TSF_CRFLAG;
                        if (cbuf[0] != '\n') {
                            ubuf[i++] = '\n';
                            len++;
                            ts->linepos--;
                        }
                    }
                    for (j = 0; i < len; i++, j++)
                        ubuf[i] = (jschar) (unsigned char) cbuf[j];
                    ts->userbuf.limit = ubuf + len;
                    ts->userbuf.ptr = ubuf;
                }
                if (ts->listener) {
                    ts->listener(ts->filename, ts->lineno, ts->userbuf.ptr, len,
                                 &ts->listenerTSData, ts->listenerData);
                }

                /*
                 * Any one of \n, \r, or \r\n ends a line (longest match wins).
                 * Also allow the Unicode line and paragraph separators.
                 */
                for (nl = ts->userbuf.ptr; nl < ts->userbuf.limit; nl++) {
                    /*
                     * Try to prevent value-testing on most characters by
                     * filtering out characters that aren't 000x or 202x.
                     */
                    if ((*nl & 0xDFD0) == 0) {
                        if (*nl == '\n')
                            break;
                        if (*nl == '\r') {
                            if (nl + 1 < ts->userbuf.limit && nl[1] == '\n')
                                nl++;
                            break;
                        }
                        if (*nl == LINE_SEPARATOR || *nl == PARA_SEPARATOR)
                            break;
                    }
                }

                /*
                 * If there was a line terminator, copy thru it into linebuf.
                 * Else copy JS_LINE_LIMIT-1 bytes into linebuf.
                 */
                if (nl < ts->userbuf.limit)
                    len = PTRDIFF(nl, ts->userbuf.ptr, jschar) + 1;
                if (len >= JS_LINE_LIMIT)
                    len = JS_LINE_LIMIT - 1;
                js_strncpy(ts->linebuf.base, ts->userbuf.ptr, len);
                ts->userbuf.ptr += len;
                olen = len;

                /*
                 * Make sure linebuf contains \n for EOL (don't do this in
                 * userbuf because the user's string might be readonly).
                 */
                if (nl < ts->userbuf.limit) {
                    if (*nl == '\r') {
                        if (ts->linebuf.base[len-1] == '\r') {
                            /*
                             * Does the line segment end in \r?  We must check
                             * for a \n at the front of the next segment before
                             * storing a \n into linebuf.  This case matters
                             * only when we're reading from a file.
                             */
                            if (nl + 1 == ts->userbuf.limit && ts->file) {
                                len--;
                                ts->flags |= TSF_CRFLAG; /* clear NLFLAG? */
                                if (len == 0) {
                                    /*
                                     * This can happen when a segment ends in
                                     * \r\r.  Start over.  ptr == limit in this
                                     * case, so we'll fall into buffer-filling
                                     * code.
                                     */
                                    return GetChar(ts);
                                }
                            } else {
                                ts->linebuf.base[len-1] = '\n';
                            }
                        }
                    } else if (*nl == '\n') {
                        if (nl > ts->userbuf.base &&
                            nl[-1] == '\r' &&
                            ts->linebuf.base[len-2] == '\r') {
                            len--;
                            JS_ASSERT(ts->linebuf.base[len] == '\n');
                            ts->linebuf.base[len-1] = '\n';
                        }
                    } else if (*nl == LINE_SEPARATOR || *nl == PARA_SEPARATOR) {
                        ts->linebuf.base[len-1] = '\n';
                    }
                }

                /* Reset linebuf based on adjusted segment length. */
                ts->linebuf.limit = ts->linebuf.base + len;
                ts->linebuf.ptr = ts->linebuf.base;

                /* Update position of linebuf within physical userbuf line. */
                if (!(ts->flags & TSF_NLFLAG))
                    ts->linepos += ts->linelen;
                else
                    ts->linepos = 0;
                if (ts->linebuf.limit[-1] == '\n')
                    ts->flags |= TSF_NLFLAG;
                else
                    ts->flags &= ~TSF_NLFLAG;

                /* Update linelen from original segment length. */
                ts->linelen = olen;
            }
            c = *ts->linebuf.ptr++;
        } while (JS_ISFORMAT(c));
    }
    if (c == '\n')
        ts->lineno++;
    return c;
}
Beispiel #5
0
//-----------------------------------------------------------------
bool t_mep_data::from_csv_double(const char *filename) 
{
	FILE *f = NULL;
#ifdef WIN32
	int count_chars = MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
	wchar_t *w_filename = new wchar_t[count_chars];
	MultiByteToWideChar(CP_UTF8, 0, filename, -1, w_filename, count_chars);

	f = _wfopen(w_filename, L"r");

	delete[] w_filename;
#else
	f = fopen(filename, "r");
#endif

	if (!f)
		return false;

	delete_data();

	char *buf = new char[MAX_ROW_CHARS];
	char * start_buf = buf;

	num_data = 0;
	data_type = MEP_DATA_DOUBLE;

	while (my_fgets(buf, MAX_ROW_CHARS, f)) {
		long len = strlen(buf);
		if (len > 1)
			num_data++;
		if (num_data == 1) {
			num_cols = 0;

			char tmp_str[1000];
			int size;
			int skipped;
			bool result = get_next_field(buf, list_separator, tmp_str, size, skipped);
			while (result) {
				num_cols++;
				if (!buf[size])
					break;
				buf = buf + size + skipped;
				result = get_next_field(buf, list_separator, tmp_str, size, skipped);

			}
			buf = start_buf;
		}
	}
	//	num_cols--;
	rewind(f);

	_data_double = new double*[num_data];
	int count_mep_data = 0;

	while (my_fgets(buf, MAX_ROW_CHARS, f)) {
		long len = strlen(buf);
		if (len > 1) {
			int col = 0;
			char tmp_str[MAX_ROW_CHARS];
			int size;
			int skipped;
			_data_double[count_mep_data] = new double[num_cols];
			bool result = get_next_field(buf, list_separator, tmp_str, size, skipped);
			while (result) {
				if (col < num_cols)
					_data_double[count_mep_data][col] = atof(tmp_str);
				else {
					break;
				}
				buf = buf + size + skipped;
				result = get_next_field(buf, list_separator, tmp_str, size, skipped);

				col++;
			}
			count_mep_data++;
		}
		buf = start_buf;
	}
	fclose(f);
	delete[] buf;
	return true;
}
Beispiel #6
0
void
read_user_pad_loc(char *pad_loc_file)
{

/* Reads in the locations of the IO pads from a file. */

    struct s_hash **hash_table, *h_ptr;
    int iblk, i, j, xtmp, ytmp, bnum, k;
    FILE *fp;
    char buf[BUFSIZE], bname[BUFSIZE], *ptr;

    printf("\nReading locations of IO pads from %s.\n", pad_loc_file);
    linenum = 0;
    fp = my_fopen(pad_loc_file, "r");

    hash_table = alloc_hash_table();
    for(iblk = 0; iblk < num_blocks; iblk++)
	{
	    if(block[iblk].type == IO_TYPE)
		{
		    h_ptr =
			insert_in_hash_table(hash_table, block[iblk].name,
					     iblk);
		    block[iblk].x = OPEN;	/* Mark as not seen yet. */
		}
	}

    for(i = 0; i <= nx + 1; i++)
	{
	    for(j = 0; j <= ny + 1; j++)
		{
		    if(grid[i][j].type == IO_TYPE)
			{
			    for(k = 0; k < IO_TYPE->capacity; k++)
				grid[i][j].blocks[k] = OPEN;	/* Flag for err. check */
			}
		}
	}

    ptr = my_fgets(buf, BUFSIZE, fp);

    while(ptr != NULL)
	{
	    ptr = my_strtok(buf, TOKENS, fp, buf);
	    if(ptr == NULL)
		{
		    ptr = my_fgets(buf, BUFSIZE, fp);
		    continue;	/* Skip blank or comment lines. */
		}

	    strcpy(bname, ptr);

	    ptr = my_strtok(NULL, TOKENS, fp, buf);
	    if(ptr == NULL)
		{
		    printf("Error:  line %d is incomplete.\n", linenum);
		    exit(1);
		}
	    sscanf(ptr, "%d", &xtmp);

	    ptr = my_strtok(NULL, TOKENS, fp, buf);
	    if(ptr == NULL)
		{
		    printf("Error:  line %d is incomplete.\n", linenum);
		    exit(1);
		}
	    sscanf(ptr, "%d", &ytmp);

	    ptr = my_strtok(NULL, TOKENS, fp, buf);
	    if(ptr == NULL)
		{
		    printf("Error:  line %d is incomplete.\n", linenum);
		    exit(1);
		}
	    sscanf(ptr, "%d", &k);

	    ptr = my_strtok(NULL, TOKENS, fp, buf);
	    if(ptr != NULL)
		{
		    printf("Error:  extra characters at end of line %d.\n",
			   linenum);
		    exit(1);
		}

	    h_ptr = get_hash_entry(hash_table, bname);
	    if(h_ptr == NULL)
		{
		    printf("Error:  block %s on line %d: no such IO pad.\n",
			   bname, linenum);
		    exit(1);
		}
	    bnum = h_ptr->index;
	    i = xtmp;
	    j = ytmp;

	    if(block[bnum].x != OPEN)
		{
		    printf
			("Error:  line %d.  Block %s listed twice in pad file.\n",
			 linenum, bname);
		    exit(1);
		}

	    if(i < 0 || i > nx + 1 || j < 0 || j > ny + 1)
		{
		    printf("Error:  block #%d (%s) location\n", bnum, bname);
		    printf("(%d,%d) is out of range.\n", i, j);
		    exit(1);
		}

	    block[bnum].x = i;	/* Will be reloaded by initial_placement anyway. */
	    block[bnum].y = j;	/* I need to set .x only as a done flag.         */

	    if(grid[i][j].type != IO_TYPE)
		{
		    printf("Error:  attempt to place IO block %s in \n",
			   bname);
		    printf("an illegal location (%d, %d).\n", i, j);
		    exit(1);
		}

	    if(k >= IO_TYPE->capacity || k < 0)
		{
		    printf
			("Error:  Block %s subblock number (%d) on line %d is out of "
			 "range.\n", bname, k, linenum);
		    exit(1);
		}
	    grid[i][j].blocks[k] = bnum;
	    grid[i][j].usage++;

	    ptr = my_fgets(buf, BUFSIZE, fp);
	}

    for(iblk = 0; iblk < num_blocks; iblk++)
	{
	    if(block[iblk].type == IO_TYPE && block[iblk].x == OPEN)
		{
		    printf
			("Error:  IO block %s location was not specified in "
			 "the pad file.\n", block[iblk].name);
		    exit(1);
		}
	}

    fclose(fp);
    free_hash_table(hash_table);
    printf("Successfully read %s.\n\n", pad_loc_file);
}
Beispiel #7
0
/* プロキシサーバのアドレスををファイルから読んで設定する */
void set_proxy(char *default_url, int default_port)
{
	char buf[1024];
	size_t len;
	FILE *fp;
	char *s;

#ifdef MACINTOSH
	int i;
	char tmp[8];
#endif

	path_build(buf, sizeof(buf), ANGBAND_DIR_PREF, "proxy.prf");

	/* ファイルから設定を読む。 */
	fp = my_fopen(buf, "r");

	if (!fp)
	{
		/* ファイルが存在しない場合はデフォルトを設定 */
		proxy = default_url;
		proxy_port = default_port;
		return;
	}

	while (my_fgets(fp, buf, sizeof(buf))==0)
	{
		if (buf[0] != '#' && buf[0] != '\0') break;
	}

	my_fclose(fp);

	/* ポインタを用意。 */
	s = buf;

	/* "http://" から始まっている場合はその部分をカットする。 */
#if defined(WINDOWS)
	if (!strnicmp(s, "http://", 7))
	{
		s += 7;
	}
#elif defined(MACINTOSH)
	strncpy( tmp , s , 7 );
	for ( i = 0 ; i < 7 ; i++ )
	{
		if ( isalpha(tmp[i]) )
			tmp[i]= tolower(tmp[i]);
	}
	if (!strncmp(s, "http://", 7))
	{
		s += 7;
	}
#else
	if (!strncasecmp(s, "http://", 7))
	{
		s += 7;
	}
#endif

	/* 文字列の長さを調べ、必要なメモリを確保 */
	len = strlen(s);
	proxy = malloc(len + 1);

	/* ポート番号があるかどうかを調べ、あればproxy_portに設定。 */
	--len;
	while (len > 0 && isdigit(s[len]))
		--len;
	if (len > 0 && s[len] == ':' && s[len + 1] != '\0')
	{
		s[len] = '\0';
		strcpy(proxy, s);
		proxy_port = atoi(s + (len + 1));
	}
	else
	{
		strcpy(proxy, s);
		proxy_port = default_port;
	}

	/* プロキシのアドレスをproxyにコピー */
	strcpy(proxy, s);

	if (proxy_port == 0)
		proxy_port = 80;
}
Beispiel #8
0
/*
 * Open the "user pref file" and parse it.
 */
static errr process_pref_file_aux(cptr name)
{
	FILE *fp;

	char buf[1024];

	char old[1024];

	int line = -1;

	errr err = 0;

	bool bypass = FALSE;


	/* Open the file */
	fp = my_fopen(name, "r");

	/* No such file */
	if (!fp) return (-1);


	/* Process the file */
	while (0 == my_fgets(fp, buf, sizeof(buf)))
	{
		/* Count lines */
		line++;


		/* Skip "empty" lines */
		if (!buf[0]) continue;

		/* Skip "blank" lines */
		if (isspace((unsigned char)buf[0])) continue;

		/* Skip comments */
		if (buf[0] == '#') continue;


		/* Save a copy */
		my_strcpy(old, buf, sizeof(old));


		/* Process "?:<expr>" */
		if ((buf[0] == '?') && (buf[1] == ':'))
		{
			char f;
			cptr v;
			char *s;

			/* Start */
			s = buf + 2;

			/* Parse the expr */
			v = process_pref_file_expr(&s, &f);

			/* Set flag */
			bypass = (streq(v, "0") ? TRUE : FALSE);

			/* Continue */
			continue;
		}

		/* Apply conditionals */
		if (bypass) continue;


		/* Process "%:<file>" */
		if (buf[0] == '%')
		{
			/* Process that file if allowed */
			(void)process_pref_file(buf + 2);

			/* Continue */
			continue;
		}


		/* Process the line */
		err = process_pref_file_command(buf);

		/* Oops */
		if (err) break;
	}


	/* Error */
	if (err)
	{
		/* Print error message */
		/* ToDo: Add better error messages */
		msg_format("Error %d in line %d of file '%s'.", err, line, name);
		msg_format("Parsing '%s'", old);
		message_flush();
	}

	/* Close the file */
	my_fclose(fp);

	/* Result */
	return (err);
}
Beispiel #9
0
bool cf_save_file(char *filename, int flags) {
	char *conf_file = filename;
	char *conf_file_dst;
	FILE *f;
	FILE *f_dst;
	int i = 0, j, a;
	char buf[512];
	char name[32];
	char val[255];
	CONF_ITEM *cf;

	if (!conf_file) {
#ifdef EMBEDDED_FS
		int len = strlen("gngeorc") + strlen(ROOTPATH"conf/") + 1;
		conf_file = (char *) alloca(len * sizeof (char));
		sprintf(conf_file, ROOTPATH"conf/gngeorc");
#elif __AMIGA__
		int len = strlen("gngeorc") + strlen("/PROGDIR/data/") + 1;
		conf_file = (char *) alloca(len * sizeof (char));
		sprintf(conf_file, "/PROGDIR/data/gngeorc");
#else /* POSIX */
		int len = strlen("gngeorc") + strlen(getenv("HOME")) + strlen("/Documents/") + 1;
		conf_file = (char *) alloca(len * sizeof (char));
		sprintf(conf_file, "%s/Documents/gngeorc", getenv("HOME"));
#endif
	}
	conf_file_dst = alloca(strlen(conf_file) + 4);
	sprintf(conf_file_dst, "%s.t", conf_file);

	if ((f_dst = fopen(conf_file_dst, "w")) == 0) {
		//printf("Unable to open %s\n",conf_file);
		return false;
	}

	if ((f = fopen(conf_file, "rb"))) {

		//printf("Loading current .cf\n");

		while (!feof(f)) {
			i = 0;
			my_fgets(buf, 510, f);
			if (discard_line(buf)) {
				fprintf(f_dst, "%s\n", buf);
				continue;
			}

			//sscanf(buf, "%s %s", name, val);
			sscanf(buf, "%s ", name);
			strncpy(val, buf + strlen(name) + 1, 254);

			cf = cf_get_item_by_name(name);
			if (cf) {
				if (cf->modified) {
					cf->modified = 0;
					switch (cf->type) {
						case CFT_INT:
							fprintf(f_dst, "%s %d\n", cf->name, CF_VAL(cf));
							break;
						case CFT_BOOLEAN:
							if (CF_BOOL(cf))
								fprintf(f_dst, "%s true\n", cf->name);
							else
								fprintf(f_dst, "%s false\n", cf->name);
							break;
						case CFT_STRING:
							fprintf(f_dst, "%s %s\n", cf->name, CF_STR(cf));
							break;
						case CFT_ARRAY:
							fprintf(f_dst, "%s ", cf->name);
							for (a = 0; a < CF_ARRAY_SIZE(cf) - 1; a++)
								fprintf(f_dst, "%d,", CF_ARRAY(cf)[a]);
							fprintf(f_dst, "%d\n", CF_ARRAY(cf)[a]);
							break;
						case CFT_ACTION:
						case CFT_ACTION_ARG:
							break;
						case CFT_STR_ARRAY:
							printf("TODO: Save CFT_STR_ARRAY\n");
							break;
					}
				} else
					fprintf(f_dst, "%s\n", buf);
			}
		}
		fclose(f);

	}
	/* Now save options that were not in the previous file */
	for (i = 0; i < 128; i++) {
		for (j = 0; j < cf_hash[i].nb_item; j++) {
			cf = cf_hash[i].conf[j];
			//printf("Option %s %d\n",cf->name,cf->modified);
			if (cf->modified!=0) {
				cf->modified=0;
				switch (cf->type) {
					case CFT_INT:
						fprintf(f_dst, "%s %d\n", cf->name, CF_VAL(cf));
						break;
					case CFT_BOOLEAN:
						if (CF_BOOL(cf))
							fprintf(f_dst, "%s true\n", cf->name);
						else
							fprintf(f_dst, "%s false\n", cf->name);
						break;
					case CFT_STRING:
						fprintf(f_dst, "%s %s\n", cf->name, CF_STR(cf));
						break;
					case CFT_ARRAY:
						fprintf(f_dst, "%s ", cf->name);
						for (a = 0; a < CF_ARRAY_SIZE(cf) - 1; a++)
							fprintf(f_dst, "%d,", CF_ARRAY(cf)[a]);
						fprintf(f_dst, "%d\n", CF_ARRAY(cf)[a]);
						break;
					case CFT_ACTION:
					case CFT_ACTION_ARG:
						/* action are not available in the conf file */
						break;
					case CFT_STR_ARRAY:
						printf("TODO: Save CFT_STR_ARRAY\n");
						break;
				}
			}
		}
	}
	fclose(f_dst);

	remove(conf_file);
	rename(conf_file_dst, conf_file);

	return true;
}
Beispiel #10
0
int readSingleFasta(FILE *fastaFile){
  int cnt;
  char ch; 
  int i,j;
  int index;
  int seqcnt=0, seqlen=0;
  int maxlen;
  char dummy[SEQ_LENGTH];
  char str[SEQ_LENGTH];

  cnt = 0; i=0;
  fprintf(stderr, "Counting sequences.\n");
  maxlen=0;
  rewind(fastaFile);
  while (fscanf(fastaFile, "%c", &ch) > 0){
    if (ch == '>'){
      if (seqlen>maxlen)
	maxlen=seqlen;
      cnt++;
      seqlen=0;
      my_fgets(dummy, SEQ_LENGTH, fastaFile);
    }
    else if (!isspace(ch))
      seqlen++;
  }

  seqcnt = cnt;
  if (seqlen>maxlen)
    maxlen=seqlen;

  //length = (int *) malloc((seqcnt) * sizeof(int));


  cnt = 0; i=0;

  fprintf(stderr, "Allocating memory for %d sequences with max length %d.\n", seqcnt, maxlen);
  
  
  seqs = (char **) malloc((seqcnt) * sizeof(char *));
  
  for (i=0; i<seqcnt; i++)
    seqs[i] = (char *) malloc(maxlen);
  

  names = (char **) malloc((seqcnt) * sizeof(char *));

  for (i=0; i<seqcnt; i++)
    names[i] = (char *) malloc(SEQ_LENGTH);
  
  
  
  for (i=0; i<seqcnt; i++){
    seqs[i][0] = 0;
    names[i][0] = 0;
  }
  

  fprintf(stderr, "Reading sequences.\n");
  rewind(fastaFile);
  cnt = -1; 
  while (fscanf(fastaFile, "%c", &ch) > 0){
    if (ch == '>'){
      cnt++;
      fprintf(stderr, "\r%d\tof\t%d", (cnt+1), seqcnt );
      my_fgets(names[cnt], SEQ_LENGTH, fastaFile);
      names[cnt][strlen(names[cnt])-1] = 0;
    }
    i = 0;
    if (cnt != 0){
      seqs[cnt][i++] = toupper(ch);
    }
    do{
      if (!(fscanf(fastaFile, "%c", &ch) > 0))
	break;
      if (ch!='>' && ch!='\r' && ch!='\n'){
	seqs[cnt][i++] = toupper(ch);
      }
    } while (ch != '>');

    seqs[cnt][i] = 0;
    
    if (ch == '>'){
      cnt++;
      fprintf(stderr, "\r%d\tof\t%d", (cnt+1), seqcnt );
      if (cnt != seqcnt){
	  my_fgets(names[cnt], SEQ_LENGTH, fastaFile);
	  names[cnt][strlen(names[cnt])-1] = 0;
      }
    } // if
  } // while
	    

  fprintf(stderr, "\n[OK] %d sequences read from fasta file.\n",seqcnt);


  return seqcnt;

}
Beispiel #11
0
/*
 * Recursive file perusal.
 *
 * Return FALSE on "ESCAPE", otherwise TRUE.
 *
 * Process various special text in the input file, including the "menu"
 * structures used by the "help file" system.
 *
 * This function could be made much more efficient with the use of "seek"
 * functionality, especially when moving backwards through a file, or
 * forwards through a file by less than a page at a time.  XXX XXX XXX
 *
 * Consider using a temporary file, in which special lines do not appear,
 * and which could be pre-padded to 80 characters per line, to allow the
 * use of perfect seeking.  XXX XXX XXX
 *
 * Allow the user to "save" the current file.  XXX XXX XXX
 */
bool show_file(cptr name, cptr what, int line, int mode)
{
	int i, k, n;

	char ch;

	/* Number of "real" lines passed by */
	int next = 0;

	/* Number of "real" lines in the file */
	int size;

	/* Backup value for "line" */
	int back = 0;

	/* This screen has sub-screens */
	bool menu = FALSE;

	/* Case sensitive search */
	bool case_sensitive = FALSE;

	/* Current help file */
	FILE *fff = NULL;

	/* Find this string (if any) */
	char *find = NULL;

	/* Jump to this tag */
	cptr tag = NULL;

	/* Hold a string to find */
	char finder[80];

	/* Hold a string to show */
	char shower[80];

	/* Filename */
	char filename[1024];

	/* Describe this thing */
	char caption[128];

	/* Path buffer */
	char path[1024];

	/* General buffer */
	char buf[1024];

	/* Lower case version of the buffer, for searching */
	char lc_buf[1024];

	/* Sub-menu information */
	char hook[10][32];

	int wid, hgt;


	/* Wipe finder */
	strcpy(finder, "");

	/* Wipe shower */
	strcpy(shower, "");

	/* Wipe caption */
	strcpy(caption, "");

	/* Wipe the hooks */
	for (i = 0; i < 10; i++) hook[i][0] = '\0';

	/* Get size */
	Term_get_size(&wid, &hgt);

	/* Copy the filename */
	my_strcpy(filename, name, sizeof(filename));

	n = strlen(filename);

	/* Extract the tag from the filename */
	for (i = 0; i < n; i++)
	{
		if (filename[i] == '#')
		{
			filename[i] = '\0';
			tag = filename + i + 1;
			break;
		}
	}

	/* Redirect the name */
	name = filename;


	/* Hack XXX XXX XXX */
	if (what)
	{
		/* Caption */
		my_strcpy(caption, what, sizeof(caption));

		/* Get the filename */
		my_strcpy(path, name, sizeof(path));

		/* Open */
		fff = my_fopen(path, "r");
	}

	/* Look in "help" */
	if (!fff)
	{
		/* Caption */
		strnfmt(caption, sizeof(caption), "Help file '%s'", name);

		/* Build the filename */
		path_build(path, sizeof(path), ANGBAND_DIR_HELP, name);

		/* Open the file */
		fff = my_fopen(path, "r");
	}

	/* Look in "info" */
	if (!fff)
	{
		/* Caption */
		strnfmt(caption, sizeof(caption), "Info file '%s'", name);

		/* Build the filename */
		path_build(path, sizeof(path), ANGBAND_DIR_INFO, name);

		/* Open the file */
		fff = my_fopen(path, "r");
	}

	/* Oops */
	if (!fff)
	{
		/* Message */
		msg_format("Cannot open '%s'.", name);
		message_flush();

		/* Oops */
		return (TRUE);
	}


	/* Pre-Parse the file */
	while (TRUE)
	{
		/* Read a line or stop */
		if (my_fgets(fff, buf, sizeof(buf))) break;

		/* XXX Parse "menu" items */
		if (prefix(buf, "***** "))
		{
			char b1 = '[', b2 = ']';

			/* Notice "menu" requests */
			if ((buf[6] == b1) && isdigit((unsigned char)buf[7]) &&
			    (buf[8] == b2) && (buf[9] == ' '))
			{
				/* This is a menu file */
				menu = TRUE;

				/* Extract the menu item */
				k = D2I(buf[7]);

				/* Extract the menu item */
				my_strcpy(hook[k], buf + 10, sizeof(hook[0]));
			}
			/* Notice "tag" requests */
			else if (buf[6] == '<')
			{
				if (tag)
				{
					/* Remove the closing '>' of the tag */
					buf[strlen(buf) - 1] = '\0';

					/* Compare with the requested tag */
					if (streq(buf + 7, tag))
					{
						/* Remember the tagged line */
						line = next;
					}
				}
			}

			/* Skip this */
			continue;
		}

		/* Count the "real" lines */
		next++;
	}

	/* Save the number of "real" lines */
	size = next;



	/* Display the file */
	while (TRUE)
	{
		/* Clear screen */
		Term_clear();


		/* Restart when necessary */
		if (line >= size) line = 0;


		/* Re-open the file if needed */
		if (next > line)
		{
			/* Close it */
			my_fclose(fff);

			/* Hack -- Re-Open the file */
			fff = my_fopen(path, "r");

			/* Oops */
			if (!fff) return (TRUE);

			/* File has been restarted */
			next = 0;
		}


		/* Goto the selected line */
		while (next < line)
		{
			/* Get a line */
			if (my_fgets(fff, buf, sizeof(buf))) break;

			/* Skip tags/links */
			if (prefix(buf, "***** ")) continue;

			/* Count the lines */
			next++;
		}


		/* Dump the next lines of the file */
		for (i = 0; i < hgt - 4; )
		{
			/* Hack -- track the "first" line */
			if (!i) line = next;

			/* Get a line of the file or stop */
			if (my_fgets(fff, buf, sizeof(buf))) break;

			/* Hack -- skip "special" lines */
			if (prefix(buf, "***** ")) continue;

			/* Count the "real" lines */
			next++;

			/* Make a copy of the current line for searching */
			my_strcpy(lc_buf, buf, sizeof(lc_buf));

			/* Make the line lower case */
			if (!case_sensitive) string_lower(lc_buf);

			/* Hack -- keep searching */
			if (find && !i && !strstr(lc_buf, find)) continue;

			/* Hack -- stop searching */
			find = NULL;

			/* Dump the line */
			Term_putstr(0, i+2, -1, TERM_WHITE, buf);

			/* Hilite "shower" */
			if (shower[0])
			{
				cptr str = lc_buf;

				/* Display matches */
				while ((str = strstr(str, shower)) != NULL)
				{
					int len = strlen(shower);

					/* Display the match */
					Term_putstr(str-lc_buf, i+2, len, TERM_YELLOW, &buf[str-lc_buf]);

					/* Advance */
					str += len;
				}
			}

			/* Count the printed lines */
			i++;
		}

		/* Hack -- failed search */
		if (find)
		{
			bell("Search string not found!");
			line = back;
			find = NULL;
			continue;
		}


		/* Show a general "title" */
		prt(format("[%s %s, %s, Line %d/%d]", VERSION_NAME,
		           VERSION_STRING, caption, line, size), 0, 0);


		/* Prompt -- menu screen */
		if (menu)
		{
			/* Wait for it */
			prt("[Press a Number, or ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- small files */
		else if (size <= hgt - 4)
		{
			/* Wait for it */
			prt("[Press ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- large files */
		else
		{
			/* Wait for it */
			prt("[Press Space to advance, or ESC to exit.]", hgt - 1, 0);
		}

		/* Get a keypress */
		ch = inkey();

		/* Return to last screen */
		if (ch == '?') break;

		/* Toggle case sensitive on/off */
		if (ch == '!')
		{
			case_sensitive = !case_sensitive;
		}

		/* Try showing */
		if (ch == '&')
		{
			/* Get "shower" */
			prt("Show: ", hgt - 1, 0);
			(void)askfor_aux(shower, sizeof(shower));

			/* Make the "shower" lowercase */
			if (!case_sensitive) string_lower(shower);
		}

		/* Try finding */
		if (ch == '/')
		{
			/* Get "finder" */
			prt("Find: ", hgt - 1, 0);
			if (askfor_aux(finder, sizeof(finder)))
			{
				/* Find it */
				find = finder;
				back = line;
				line = line + 1;

				/* Make the "finder" lowercase */
				if (!case_sensitive) string_lower(finder);

				/* Show it */
				my_strcpy(shower, finder, sizeof(shower));
			}
		}

		/* Go to a specific line */
		if (ch == '#')
		{
			char tmp[80];
			prt("Goto Line: ", hgt - 1, 0);
			strcpy(tmp, "0");
			if (askfor_aux(tmp, sizeof(tmp)))
			{
				line = atoi(tmp);
			}
		}

		/* Go to a specific file */
		if (ch == '%')
		{
			char ftmp[80];
			prt("Goto File: ", hgt - 1, 0);
			strcpy(ftmp, "help.hlp");
			if (askfor_aux(ftmp, sizeof(ftmp)))
			{
				if (!show_file(ftmp, NULL, 0, mode)) ch = ESCAPE;
			}
		}

		/* Back up one line */
		if (ch == '=')
		{
			line = line - 1;
			if (line < 0) line = 0;
		}

		/* Back up one half page */
		if (ch == '_')
		{
			line = line - ((hgt - 4) / 2);
			if (line < 0) line = 0;
		}

		/* Back up one full page */
		if (ch == '-')
		{
			line = line - (hgt - 4);
			if (line < 0) line = 0;
		}

		/* Advance one line */
		if ((ch == '\n') || (ch == '\r'))
		{
			line = line + 1;
		}

		/* Advance one half page */
		if (ch == '+')
		{
			line = line + ((hgt - 4) / 2);
			if (line < 0) line = 0;
		}

		/* Advance one full page */
		if (ch == ' ')
		{
			line = line + (hgt - 4);
		}

		/* Recurse on numbers */
		if (menu && isdigit((unsigned char)ch) && hook[D2I(ch)][0])
		{
			/* Recurse on that file */
			if (!show_file(hook[D2I(ch)], NULL, 0, mode)) ch = ESCAPE;
		}

		/* Exit on escape */
		if (ch == ESCAPE) break;
	}

	/* Close the file */
	my_fclose(fff);

	/* Done */
	return (ch != ESCAPE);
}
void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen)
{
    int     n = 0;
    int     maxfdp1 = 0;
    const   int     on = 1;
    char    sendline[MAXLINE] = {0};
    char    recvline[MAXLINE] = {0};
    fd_set  rset;
    socklen_t   len;
    struct  sockaddr    *preply_addr = NULL;

    preply_addr = my_malloc(servlen);

    my_setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));

    my_pipe(pipefd);
//    printf("pipefd[0] = %d\n", pipefd[0]); //+

    maxfdp1 = max(sockfd, pipefd[0]) + 1;

    FD_ZERO(&rset);

    my_signal(SIGALRM, recvfrom_alarm);

    while (my_fgets(sendline, MAXLINE, fp) != NULL )
    {
        my_sendto(sockfd, sendline, strlen(sendline),
                  0, pservaddr, servlen);

        alarm(3);

        while (1)
        {
            FD_SET(sockfd, &rset);
            FD_SET(pipefd[0], &rset);

            if ( (n = select(maxfdp1, &rset, NULL, NULL, NULL)) < 0 )
            {
                if (errno == EINTR)
                {
                    DEBUG;
                    printf("select errno = EINTR\n");    //+
                    continue;
                }
                else
                {
                    err_sys("select error");
                }
            }
//                printf("kankan!\n");
            if ( FD_ISSET(sockfd, &rset) )
            {
                len = servlen;
                n = my_recvfrom(sockfd, recvline, MAXLINE,
                                0, preply_addr, &len);
                recvline[n] = 0;
                printf("from %s: %s",
                       my_sock_ntop(preply_addr, len),
                       recvline);
            }

            if ( FD_ISSET(pipefd[0], &rset) )
            {
//                   printf("read 上面\n");
                my_read(pipefd[0], &n, 1);   //timer expired
//                   printf("read 下面!\n");
                break;
            }
        }
    }

    free(preply_addr);

}
Beispiel #13
0
static void parse_name_and_pinlist (int doall, FILE *fp_net, char *buf) {

/* This routine does the first part of the parsing of a block.  It is *
 * called whenever any type of block (.clb, .input or .output) is to  *
 * be parsed.  It increments the block count (num_blocks), and checks *
 * that the block has a name.  If doall is 1, this is the loading     *
 * pass and it copies the name to the block data structure.  Finally  *
 * it checks that the pinlist: keyword exists.  On return, my_strtok  *
 * is set so that the next call will get the first net connected to   *
 * this block.                                                        */

 char *ptr;
 int len;
 
/* Get block name. */
 
 ptr = my_strtok(NULL,TOKENS,fp_net,buf);
 if (ptr == NULL) {
    printf("Error in parse_name_and_pinlist on line %d of netlist file.\n",
       linenum);
    printf(".clb, .input or .output line has no associated name.\n");
    exit (1);
 }
 
 if (doall == 1) {    /* Second (loading) pass, store block name */
    len = strlen (ptr);
    block[num_blocks-1].name = my_chunk_malloc ((len + 1) * sizeof(char),
                  NULL, &chunk_bytes_avail, &chunk_next_avail_mem);
    strcpy (block[num_blocks-1].name, ptr);
 }
 
 ptr = my_strtok (NULL,TOKENS,fp_net,buf);
 if (ptr != NULL) {
    printf("Error in parse_name_and_pinlist on line %d of netlist file.\n",
       linenum);
    printf("Extra characters at end of line.\n");
    exit (1);
 }
 
/* Now get pinlist from the next line.  Note that a NULL return value *
 * from my_gets means EOF, while a NULL return from my_strtok just    *
 * means we had a blank or comment line.                              */
 
 do {
    ptr = my_fgets (buf, BUFSIZE, fp_net);
    if (ptr == NULL) {
       printf("Error in parse_name_and_pinlist on line %d of netlist file.\n",
          linenum);
       printf("Missing pinlist: keyword.\n");
       exit (1);
    }

    ptr = my_strtok(buf,TOKENS,fp_net,buf);
 } while (ptr == NULL);
 
 if (strcmp (ptr, "pinlist:") != 0) {
    printf("Error in parse_name_and_pinlist on line %d of netlist file.\n",
       linenum);
    printf("Expected pinlist: keyword, got %s.\n",ptr);
    exit (1);
 }
}
Beispiel #14
0
static struct ppdent *getppdent( FILE *stream)
{
    static char			buf[ 1024 ];
    static struct ppdent	ppdent;
    char			*p, *q;

    ppdent.pe_main = ppdent.pe_option = ppdent.pe_translation =
	    ppdent.pe_value = NULL;

    while (( p = my_fgets( buf, sizeof( buf ), stream )) != NULL ) {
	if ( *p != '*' ) {	/* main key word */
	    continue;
	}
	if ( p[ strlen( p ) - 1 ] != '\n') {
	    LOG(log_error, logtype_papd, "getppdent: line too long" );
	    continue;
	}

	q = p;
	while ( (*p != ' ') && (*p != '\t') && (*p != ':') && (*p != '\n') ) {
	    p++;
	}
	if ( (*( q + 1 ) == '%') || (*( q + 1 ) == '?') ) {	/* comments & queries */
	    continue;
	}
	ppdent.pe_main = q;
	if ( *p == '\n' ) {
	    *p = '\0';
	    ppdent.pe_option = ppdent.pe_translation = ppdent.pe_value = NULL;
	    return( &ppdent );
	}

	if ( *p != ':' ) {	/* option key word */
	    *p++ = '\0';

	    while ( (*p == ' ') || (*p == '\t') ) {
		p++;
	    }

	    q = p;
	    while ( (*p != ':') && (*p != '/') && (*p != '\n') ) {
		p++;
	    }

	    if ( *p == '\n' ) {
		continue;
	    }

	    ppdent.pe_option = q;
	    if ( *p == '/' ) {	/* translation string */
		*p++ = '\0';
		q = p;
		while ( *p != ':' && *p != '\n' ) {
		    p++;
		}
		if ( *p != ':' ) {
		    continue;
		}

		ppdent.pe_translation = q;
	    } else {
		ppdent.pe_translation = NULL;
	    }
	}
	*p++ = '\0';

	while ( (*p == ' ') || (*p == '\t') ) {
	    p++;
	}

	/* value */
	q = p;
	while ( *p != '\n' ) {
	    p++;
	}
	*p = '\0';
	ppdent.pe_value = q;

	return( &ppdent );
    }

    return( NULL );
}
Beispiel #15
0
void process_dialog_declaration( FILE *fi, FILE *fo, char *line )
/***************************************************************/
{
    long    font_size = 0;
    char    *font_name = NULL;
    char    *separators = " \t,|";
    int     font_set = 0;
    int     hidden_dialog = 0;
    char    *buff1;
    char    *p;
    char    **p2;
    size_t  len;
    int     sysmodal, visible;
    int     i;
    
    ++dialogs_cnt;
    if( opt.quiet == 0 ) {
        fprintf( stdout, "." );
    }
    // process DIALOG line
    buff1 = malloc( MAX_LINE_LEN );
    strcpy( buff1, skip_separator( line ) );
    p = strtok( buff1, separators );
    if( p != NULL )
        strcpy( dlg_hdr.ID, p );
    p = strtok( NULL, " ,\t" );
    while(( p != NULL ) && !isdigit( *p ) )
        p = strtok( NULL, separators );
    if( p != NULL )
        dlg_hdr.x = atoi( p ) * CONV_X;
    p = strtok( NULL, separators );
    if( p != NULL )
        dlg_hdr.y = atoi( p ) * CONV_Y;
    p = strtok( NULL, separators );
    if( p != NULL )
        dlg_hdr.dx = atoi( p ) * CONV_X;
    p = strtok( NULL, separators );
    if( p != NULL )
        dlg_hdr.dy = atoi( p ) * CONV_Y;
    dlg_hdr.y = 230 - dlg_hdr.y - dlg_hdr.dy;
    strcpy( dlg_hdr.text, "\"\"" );
    // process next lines
    my_fgets( line, MAX_LINE_LEN, fi );
    while(( *line != '\0' ) && ( strstr( line, "BEGIN" ) == NULL )) {
        strcpy( buff1, line );
        strtok( buff1, separators );
        if( strstr( line, "STYLE" ) != NULL ) {
            add_parms_list( &dlg_hdr, separators, 1 );
            len = strlen( line );
            for( p = line + len - 1; len && isspace( *p ); --len )
                *(p--) = '\0';
            if( *p == '|' ) {
                my_fgets( line, MAX_LINE_LEN, fi );
                strcpy( buff1, line );
                p = strtok( buff1, separators );
                while( p != NULL ) {
                    add_parms_item( dlg_hdr.parms, p, ADD_AFTER );
                    p = strtok( NULL, separators );
                }
            }
        } else if( (p = strstr( line, "CAPTION" )) != NULL ) {
            strcpy( dlg_hdr.text, p + 8 );
            dlg_hdr.text[ strlen( dlg_hdr.text ) ] = '\0';
        } else if( strstr( line, "FONT" ) != NULL ) {
            font_set = 1;
            p = strtok( NULL, separators );
            font_size = strtol( p, &p, 10 );
            p = strtok( NULL, "\"" );
            p = strtok( NULL, "\"" );
            if( opt.font ) {
                font_name = malloc( strlen( opt.font_name ) + 1 );
                strcpy( font_name, opt.font_name );
                if( opt.font_size != 0 ) {
                    font_size = opt.font_size;
                }
            } else {
                if( p != NULL ) {
                    font_name = malloc( strlen( p ) + 10 );
                    strcpy( font_name, p );
                    p2 = malloc( sizeof(char *) );
                    *p2 = font_name;
                    convert_font( p2, 1 );
                    free( p2 );
                }
            }
        }
        my_fgets( line, MAX_LINE_LEN, fi );
    }
    process_style( dlg_hdr.parms, "DIALOG" );
    if( font_set == 0 ) {
        font_name = malloc( 7 );
        strcpy( font_name, "Helv" );
        font_size = 10;
    }
    sysmodal = process_parms( dlg_hdr.parms, MAX_STMT_PARMS, control_class_win,
        control_class_os2, CTRL_NAME_CNT, 0, check_parm_item, "FCF_SYSMODAL" );
    if( opt.hide ) {
        for( i = 0; i < opt.flist_cnt; ++i ) {
            if( stricmp( dlg_hdr.ID, opt.flist_data[ i ] ) == 0 ) {
                hidden_dialog = 1;
                break;
            }
        }
    }
    visible = process_parms( dlg_hdr.parms, MAX_STMT_PARMS, control_class_win,
        control_class_os2, CTRL_NAME_CNT, 0, check_parm_item, "WS_VISIBLE" );
    fprintf( fo, "DLGTEMPLATE %s\n", dlg_hdr.ID );
    fprintf( fo, "BEGIN\n%sDIALOG %s, %s, %d, %d, %d, %d, ", STR_SPC, dlg_hdr.text,
               dlg_hdr.ID, dlg_hdr.x, dlg_hdr.y, dlg_hdr.dx, dlg_hdr.dy );
    if( hidden_dialog ) {
        fprintf( fo, "FS_BORDER | NOT FS_DLGBORDER | NOT WS_VISIBLE\n" );
    } else {
#if defined( OLD_FORMAT )
        if( sysmodal && visible ) {
            fprintf( fo, "FS_SYSMODAL\n\t\t| WS_VISIBLE" );
        } else if( sysmodal ) {
            fprintf( fo, "FS_SYSMODAL\n\t\t" );
        } else if( visible ) {
            fprintf( fo, "WS_VISIBLE\n\t\t" );
        } else {
            fprintf( fo, "0L\n\t\t" );
        }
#else
        if( sysmodal && visible ) {
            fprintf( fo, "\n\t\tFS_SYSMODAL | WS_VISIBLE" );
        } else if( sysmodal ) {
            fprintf( fo, "\n\t\tFS_SYSMODAL" );
        } else if( visible ) {
            fprintf( fo, "\n\t\tWS_VISIBLE" );
        } else {
            fprintf( fo, "\n\t\t0L" );
        }
#endif
        out_parms_style( fo, dlg_hdr.parms, "DIALOG" );
    }
    if(( font_name != NULL ) || ( font_size != 0 )) {
        fprintf( fo, "%sPRESPARAMS PP_FONTNAMESIZE, ", STR_SPC );
        if( font_size != 0 ) {
            fprintf( fo, "\"%ld.%s\"\n", font_size, font_name );
        } else {
            fprintf( fo, "\"%s\"\n", font_name );
        }
        free( font_name );
    }
    fprintf( fo, "%sBEGIN\n", STR_SPC );
    free( buff1 );
}
Beispiel #16
0
bool cf_open_file(char *filename) {
	/* if filename==NULL, we use the default one: $HOME/Documents/gngeorc */
	char *conf_file = filename;
	FILE *f;
	int i = 0;
	char buf[512];
	char name[32];
	char val[255];
	CONF_ITEM *cf;

	if (!conf_file) {
#ifdef EMBEDDED_FS
		int len = strlen("gngeorc") + strlen(ROOTPATH"conf/") + 1;
		conf_file = (char *) alloca(len * sizeof (char));
		sprintf(conf_file, ROOTPATH"conf/gngeorc");
#elif __AMIGA__
		int len = strlen("gngeorc") + strlen("/PROGDIR/data/") + 1;
		conf_file = (char *) alloca(len * sizeof (char));
		sprintf(conf_file, "/PROGDIR/data/gngeorc");
#else
		int len = strlen("gngeorc") + strlen(getenv("HOME")) + strlen("/Documents/") + 1;
		conf_file = (char *) alloca(len * sizeof (char));
		sprintf(conf_file, "%s/Documents/gngeorc", getenv("HOME"));
#endif
	}
	if ((f = fopen(conf_file, "rb")) == 0) {
		//printf("Unable to open %s\n",conf_file);
		return false;
	}

	while (!feof(f)) {
		i = 0;
		my_fgets(buf, 510, f);
		if (discard_line(buf))
			continue;
	
		/* TODO: Verify this on Win32 */
		sscanf(buf, "%s %s", name, val);

		//sscanf(buf, "%s ", name);
		//strncpy(val,buf+strlen(name)+1,254);

//		printf("%s|%s|\n",name,val);
		cf = cf_get_item_by_name(name);
		if (cf && !(cf->flags & CF_SETBYCMD) && (!cf->modified)) {
//			printf("Option %s\n",cf->name);
			switch (cf->type) {
				case CFT_INT:
					CF_VAL(cf) = atoi(val);
//                    printf("got val: %d\n",CF_VAL(cf));
					break;
				case CFT_BOOLEAN:
					CF_BOOL(cf) = (strcasecmp(val, "true") == 0 ? true : false);
					break;
				case CFT_STRING:
					strncpy(CF_STR(cf), val, 254);
					break;
				case CFT_ARRAY:
					read_array(CF_ARRAY(cf), val, CF_ARRAY_SIZE(cf));
					break;
				case CFT_ACTION:
				case CFT_ACTION_ARG:
					/* action are not available in the conf file */
					break;
				case CFT_STR_ARRAY:
					CF_STR_ARRAY(cf) = read_str_array(val, &CF_STR_ARRAY_SIZE(cf));
					break;
			}
		} else {
			/*printf("Unknow option %s\n",name);*/
			/* unknow option...*/
		}
	}

	cf_cache_conf();
	return true;
}
Beispiel #17
0
int main( int argc, char *argv[] )
/********************************/
{
    char    fname[ PATH_MAX ];
    FILE    *fi;
    FILE    *fo;
    char    *p;
    int     i;
    char    *line;
    char    *buff1;
    char    *buff2;
    char    *separators = " \t";
    
    i = process_cmdl( argc, argv );
    if( i == 0 ) {
        disp_usage();
        return( -1 );
    }
    strcpy( fname, argv[ i ] );
    if( strrchr( fname, '.' ) == NULL )
        strcat( fname, ".dlg" );
    fi = fopen( fname, "r" );
    if( fi == NULL ) {
        printf( "Could not open input file: %s\n", fname );
        return( -1 );
    }
    if( i + 1 < argc ) {
        strcpy( fname, argv[ i + 1 ] );
        if( strrchr( fname, '.' ) == NULL ) {
            strcat( fname, ".dlg" );
        }
    } else {
        strcpy( fname, "os2dlg.dlg" );
    }
    fo = fopen( fname, "w" );
    if( fo == NULL ) {
        printf( "Could not open input file: %s\n", fname );
        return( -1 );
    }
    
    alloc_statement( &dlg_hdr );
    alloc_statement( &dlg_item );

    line = malloc( MAX_LINE_LEN );
    
    buff1 = malloc( MAX_LINE_LEN );
    buff2 = malloc( MAX_LINE_LEN );
    
    my_fgets( line, MAX_LINE_LEN, fi );
    while( !feof( fi ) ) {
        while( !feof( fi ) ) {
            if( strstr( line, "DLGINCLUDE" ) != NULL ) {
                /**********************
                 * source file format:
                 *
                 * DLGINCLUDE
                 * BEGIN
                 * filename
                 * END
                 *
                 * converted to:
                 *
                 * DLGINCLUDE 1 filename
                 */
                p = malloc( MAX_LINE_LEN );
                strcpy( p, line );
                fprintf( fo, "%s 1 ", strtok( p, separators ) );
                my_fgets( line, MAX_LINE_LEN, fi );
                my_fgets( line, MAX_LINE_LEN, fi );
                strcpy( p, line );
                fprintf( fo, "%s\n", strtok( p, separators ) );
                free( p );
                my_fgets( line, MAX_LINE_LEN, fi );
                my_fgets( line, MAX_LINE_LEN, fi );
            } else if( strstr( line, "DIALOG" ) != NULL ) {
                p = malloc( MAX_LINE_LEN );
                strcpy( p, line );
                process_dialog_declaration( fi, fo, p );
                strcpy( line, p );
                free( p );
            } else if( strstr( line, "BEGIN" ) != NULL ) {
                my_fgets( line, MAX_LINE_LEN, fi );
                break;
            } else {
#if !defined( OLD_FORMAT )
                if( *line != '\0' )
#endif
                fprintf( fo, "%s\n", line );
                my_fgets( line, MAX_LINE_LEN, fi );
            }
        }
        p = "";
        while( !feof( fi ) && strcmp( p, "END" ) ) {
            while( my_fgets( buff1, MAX_LINE_LEN, fi ) != NULL ) {
                if( check_statement( buff1 ) )
                    break;
                strncat( line, skip_separator( buff1 ), MAX_LINE_LEN );
            }
            process_statement( line, fo );
            strcpy( line, buff1 );
            strcpy( buff2, buff1 );
            p = strtok( buff2, separators );
        }
        if( !feof( fi ) ) {
            fprintf( fo, "%sEND\n", STR_SPC );
        }
    }
    free( buff2 );
    free( buff1 );

    free( line );
    
    free_statement( &dlg_item );
    free_statement( &dlg_hdr );
    if( fi != NULL )
        fclose( fi );
    if( fo != NULL ) {
#if defined( OLD_FORMAT )
        fprintf( fo, "\n" );
#endif
        fclose( fo );
    }
    if( !opt.quiet )
        fprintf( stdout, "\nParsed %d dialogs.\n", dialogs_cnt );
    if( opt.flist_data ) {
        for( i = 0; i < opt.flist_cnt; i++ )
            free( opt.flist_data[ i ] );
        free( opt.flist_data );
    }
    return( 0 );
}
Beispiel #18
0
//-----------------------------------------------------------------
bool t_mep_data::from_PROBEN1_format(const char *filename, int num_classes)
{
	FILE *f = NULL;
#ifdef WIN32
	int count_chars = MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
	wchar_t *w_filename = new wchar_t[count_chars];
	MultiByteToWideChar(CP_UTF8, 0, filename, -1, w_filename, count_chars);

	f = _wfopen(w_filename, L"r");

	delete[] w_filename;
#else
	f = fopen(filename, "r");
#endif

	if (!f)
		return false;

	delete_data();

	char *buf = new char[MAX_ROW_CHARS];
	char * start_buf = buf;

	num_data = 0;
	data_type = MEP_DATA_DOUBLE;

	while (my_fgets(buf, MAX_ROW_CHARS, f)) {
		long len = strlen(buf);
		if (len > 1)
			num_data++;
		if (num_data == 1) {
			num_cols = 0;

			char tmp_str[1000];
			int size;
			int skipped;
			bool result = get_next_field(buf, ' ', tmp_str, size, skipped);
			while (result) {
				num_cols++;
				if (!buf[size])
					break;
				buf = buf + size + skipped;
				result = get_next_field(buf, ' ', tmp_str, size, skipped);

			}
			buf = start_buf;
		}
	}
	num_cols -= num_classes;
	if (num_classes)
	  num_cols++;

	rewind(f);

	_data_double = new double*[num_data];

	int out_class;
	for (int r = 0; r < num_data; r++) {
		_data_double[r] = new double[num_cols];
		for (int c = 0; c < num_cols - 1; c++)
			fscanf(f, "%lf", &_data_double[r][c]);
		// now scan the outputs
		if (num_classes) // classification problem
		for (int c = 0; c < num_classes; c++) {
			fscanf(f, "%d", &out_class);
			if (out_class == 1)
				_data_double[r][num_cols - 1] = c;
		}
		else// regression problem
			fscanf(f, "%lf", &_data_double[r][num_cols - 1]);
	}

	fclose(f);
	delete[] buf;
	return true;

}
Beispiel #19
0
int main(int argc, char *argv[]) {
  int notdone=1;
  char buf[1024];
  int val[9], i, ch, code;
  time_t starttime, curtime;
  struct timeval tv;
  struct timezone tz;
  struct tm *ltime;
  int interval = 1;

  setup_vars();
  
  printf("Hello, World!\n");
  if (get_args(argc, argv) != 0) {
    show_usage();
    exit(1);
  }
  for(ch=0;ch<CHMAX;ch++) {
    clear_reading_storage(ch);
  }
  clear_inputs(interval);
  make_line();
  if ((fd = open(dsrc, O_RDWR|O_NONBLOCK)) < 0) {
    printf("couldn't open data source file\n");
    exit(1);
  }
  start_serial_io(fd, baud);
  my_fgets(buf, 1000, fd);
  notdone = 0;
  printf("syncing time...\n");
  while (notdone < 2) {
    starttime = time(NULL);
    ltime = localtime(&starttime);
    if ((ltime->tm_sec % interval) == 0) {
      notdone++;
    } else {
      /* sleep(1); */
      my_fgets(buf, 1000, fd);
    }
    curday = ltime->tm_mday;
    set_curdatestring(ltime);
  }
  if (log_file_name != NULL) {
    start_log_file();
  }
  printf("starting at %010d\n", (int) starttime);
  notdone = 1;
  while (notdone) {
    /* take care of time first */
    curtime = time(NULL);
    if (curtime >= (starttime + interval)) {
      if (logfp != NULL) {
        fprintf(logfp, "%010d (%s)", (int) starttime, safe_ctime(&starttime));
      } else {
        printf("%010d (%s)", (int) starttime, safe_ctime(&starttime));
      }
      for (ch=0;ch<CHMAX;ch++) {
        dump_reading(ch);
        clear_reading_storage(ch);
      }
      /* dump_inputs(); */
      if (logfp != NULL) {
        fprintf(logfp, "\n");
      } else {
        printf("\n");
      }
      starttime = curtime;
      ltime = localtime(&curtime); /* ltime is needed here and ctime messes it up */
      /* check for the day change here so that the last second of yesterday
         ends up in *yesterday's* log and this days data ends up in this
         days log */
      if (ltime->tm_mday != curday) {
        set_curdatestring(ltime);
        if (log_file_name != NULL) {
          fclose(logfp);
          start_log_file();
        }
        curday = ltime->tm_mday;
      } else {
        /* flush whenever a line is written */
        if (logfp != NULL) {
          fflush(logfp);
        } else {
          fflush(stdout);
        }
      }
    }
    if (my_fgets(buf, 1000, fd) == 1) {
      if (strlen(buf) > 4) {
        /* printf("%s", buf); */
        buf[strlen(buf) - 1] = 0;
        chop_input(buf, val, &code);
        /* test_code_change(~code, curtime); */
        for (ch=0;ch<CHMAX;ch++) {
          add_reading(ch, val[ch+1]);
        }
      }
    } else { /* don't consume 100% of the processor. */
      usleep(1000);
    }
    fflush(stdout);
  }
  exit(0);
}
Beispiel #20
0
//-----------------------------------------------------------------
bool t_mep_data::from_csv_string(const char *filename) 
{
	FILE *f = NULL;
#ifdef WIN32
	int count_chars = MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
	wchar_t *w_filename = new wchar_t[count_chars];
	MultiByteToWideChar(CP_UTF8, 0, filename, -1, w_filename, count_chars);

	f = _wfopen(w_filename, L"r");

	delete[] w_filename;
#else
	f = fopen(filename, "r");
#endif

	if (!f)
		return false;

	delete_data();

	char *buf = new char[MAX_ROW_CHARS];
	char * start_buf = buf;

	data_type = MEP_DATA_STRING;
	num_data = 0;

	while (my_fgets(buf, MAX_ROW_CHARS, f)) {
		long len = strlen(buf);
		if (len > 1)
			num_data++;
		if (num_data == 1) {
			num_cols = 0;
			int skipped;

			char tmp_str[1000];
			int size;
			bool result = get_next_field(buf, list_separator, tmp_str, size, skipped);
			while (result) {
				num_cols++;
				if (!buf[size + skipped])
					break;
				buf = buf + size + skipped;
				result = get_next_field(buf, list_separator, tmp_str, size, skipped);
			}
			buf = start_buf;
		}
	}
	//	num_cols--;
	rewind(f);

	_data_string = new char**[num_data];
	int count_mep_data = 0;
	//has_missing_values = 0;

	while (my_fgets(buf, MAX_ROW_CHARS, f)) {
		long len = strlen(buf);
		if (len > 1) {
			int col = 0;
			char tmp_str[1000];
			int size;
			_data_string[count_mep_data] = new char*[num_cols];
			for (int c = 0; c < num_cols; c++)
				_data_string[count_mep_data][col] = NULL;

			int skipped = 0;
			bool result = get_next_field(buf, list_separator, tmp_str, size, skipped);
			while (result) {
				if (col < num_cols) {
					_data_string[count_mep_data][col] = new char[strlen(tmp_str) + 1];
					strcpy(_data_string[count_mep_data][col], tmp_str);
				}
				else {
					break;
				}
				buf = buf + size + skipped;
				//if (buf - start_buf >= len)
				//break;
				result = get_next_field(buf, list_separator, tmp_str, size, skipped);

				col++;
			}
			count_mep_data++;
		}
		buf = start_buf;
	}
	fclose(f);
	//delete[] start_buf;
	delete[] buf;
	return true;
}
Beispiel #21
0
void set_proxy(char *default_url, int default_port)
{
	char buf[1024];
	size_t len;
	FILE *fp;
	char *s;

#ifdef MACINTOSH
	int i;
	char tmp[8];
#endif

	path_build(buf, sizeof(buf), ANGBAND_DIR_PREF, "proxy.prf");

	fp = my_fopen(buf, "r");

	if (!fp)
	{
		proxy = default_url;
		proxy_port = default_port;
		return;
	}

	while (my_fgets(fp, buf, sizeof(buf))==0)
	{
		if (buf[0] != '#' && buf[0] != '\0') break;
	}

	my_fclose(fp);

	s = buf;

#if defined(WINDOWS)
	if (!strnicmp(s, "http://", 7))
	{
		s += 7;
	}
#elif defined(MACINTOSH)
	strncpy( tmp , s , 7 );
	for ( i = 0 ; i < 7 ; i++ )
	{
		if ( isalpha(tmp[i]) )
			tmp[i]= tolower(tmp[i]);
	}
	if (!strncmp(s, "http://", 7))
	{
		s += 7;
	}
#else
	if (!strncasecmp(s, "http://", 7))
	{
		s += 7;
	}
#endif

	len = strlen(s);
	proxy = malloc(len + 1);

	--len;
	while (len > 0 && isdigit(s[len]))
		--len;
	if (len > 0 && s[len] == ':' && s[len + 1] != '\0')
	{
		s[len] = '\0';
		strcpy(proxy, s);
		proxy_port = atoi(s + (len + 1));
	}
	else
	{
		strcpy(proxy, s);
		proxy_port = default_port;
	}

	strcpy(proxy, s);

	if (proxy_port == 0)
		proxy_port = 80;
}
Beispiel #22
0
/*
 * Hack -- load a screen dump from a file
 */
void do_cmd_load_screen(void)
{
	s32b i, y, x;

	s32b wid, hgt;
	s32b len;

	byte a = 0;
	char c = ' ';

	bool okay = TRUE;

	PHYSFS_file *fff;

	char buf[1024];


	/* Build the filename */
	path_build(buf, 1024, TENGINE_DIR_USER, "dump.txt");

	/* Append to the file */
	fff = my_fopen(buf, "r");

	/* Oops */
	if (!fff) return;


	/* Retrieve the current screen size */
	Term_get_size(&wid, &hgt);

	/* Enter "icky" mode */
	character_icky++;

	/* Save the screen */
	Term_save();

	/* Clear the screen */
	Term_clear();


	/* Load the screen */
	for (y = 0; okay; y++)
	{
		/* Get a line of data */
		if (my_fgets(fff, buf, 1024)) okay = FALSE;

		/* Stop on blank line */
		if (!buf[0]) break;

		/* Ignore off screen lines */
		if (y >= hgt) continue;

		/* Get width */
		len = strlen(buf);

		/* Truncate if it's longer than current screen width */
		if (len > wid) len = wid;

		/* Show each row */
		for (x = 0; x < len; x++)
		{
			/* Put the attr/char */
			Term_draw(x, y, TERM_WHITE, buf[x]);
		}
	}

	/* Dump the screen */
	for (y = 0; okay; y++)
	{
		/* Get a line of data */
		if (my_fgets(fff, buf, 1024)) okay = FALSE;

		/* Stop on blank line */
		if (!buf[0]) break;

		/* Ignore off screen lines */
		if (y >= hgt) continue;

		/* Get width */
		len = strlen(buf);

		/* Truncate if it's longer than current screen width */
		if (len > wid) len = wid;

		/* Dump each row */
		for (x = 0; x < len; x++)
		{
			/* Get the attr/char */
			(void)(Term_what(x, y, &a, &c));

			/* Look up the attr */
			for (i = 0; i < 16; i++)
			{
				/* Use attr matches */
				if (hack[i] == buf[x]) a = i;
			}

			/* Hack -- fake monochrome */
			if (!use_color) a = TERM_WHITE;

			/* Put the attr/char */
			Term_draw(x, y, a, c);
		}
	}


	/* Close it */
	my_fclose(fff);


	/* Message */
	msg_print("Screen dump loaded.");
	msg_print(NULL);


	/* Restore the screen */
	Term_load();

	/* Leave "icky" mode */
	character_icky--;
}