Ejemplo n.º 1
0
void ImageDialog::nextImage()
{
	if (currentIndex+1<currentList.size())
	{
		QString nextfile(currentPath);
		QString currentFile_onlyname=currentList.at(++currentIndex);
		nextfile.append(tr("/")).append(currentFile_onlyname);
		lastFileName=nextfile;
		//rawString= nextfile.toStdString();
		rawString = nextfile;
		LoadRawStream();
		GenUnclassifyImage(tjImage,unclassifiedImage);
		(*processUnclassifiedImage)=(*unclassifiedImage);
		if(lut_ != NULL)
		{
			GenClassifyImage(lut_,tjImage,classifiedImage);
			processImage();
			DrawVisualObjects(processUnclassifiedImage);
		}
		update();
		show();
		raise();
		activateWindow();
	}
	else
		QMessageBox::information(this,tr("Warning"),tr("TO THE END"));
}
Ejemplo n.º 2
0
static void
split(const char *fn)
{
	FILE	*fp, *op = NULL;
	long long	bytes = bytecount, lines = linecount, n, m;
	char	b[4096];
	int	c;

	if (fn[0] == '-' && fn[1] == '\0')
		fp = stdin;
	else if ((fp = fopen(fn, "r")) == NULL) {
		fprintf(stderr, "cannot open input");
		exit(1);
	}
	if (linecount > 0) {
		while ((c = getc(fp)) != EOF) {
			if (lines >= linecount) {
				lines = 0;
				if (op)
					fclose(op);
				op = nextfile();
			}
			putc(c, op);
			if (c == '\n')
				lines++;
		}
	} else {
		do {
			if ((n = bytecount - bytes) > sizeof b)
				n = sizeof b;
			else if (n == 0 && (n = bytecount) > sizeof b)
				n = sizeof b;
			m = fread(b, 1, n, fp);
			if (bytes >= bytecount) {
				bytes = 0;
				if (op)
					fclose(op);
				op = nextfile();
			}
			if (m) {
				fwrite(b, 1, m, op);
				bytes += m;
			}
		} while (m);
	}
}
Ejemplo n.º 3
0
static struct cbfile *findfile(const char *filename)
{
	struct cbfile *f;
	for (f = firstfile(); f; f = nextfile(f)) {
		if (strcmp(filename, f->filename) == 0)
			return f;
	}
	return NULL;
}
Ejemplo n.º 4
0
int
matchfile(Resub *match)
{
	if(match[1].sp) {
		int len = match[1].ep - match[1].sp;

		strncpy(name, match[1].sp, len);
		strcpy(name+len, suffix);
		openf();
		return 1;
	} 
	return nextfile();
}
Ejemplo n.º 5
0
static int cbfs_module_init(void)
{
	struct cbfile *f;
	int index = 0;

	header = *(void **)HEADER_ADDR;
	if (header->magic != ntohl(HEADER_MAGIC)) {
		header = NULL;
		return 0;
	}

	for (f = firstfile(); f; f = nextfile(f))
		filecount++;

	filenames = malloc(filecount * sizeof(char *));
	if (filenames == NULL)
		return 0;

	for (f = firstfile(); f; f = nextfile(f))
		filenames[index++] = strdup((const char *)f->filename);

	return 0;
}
Ejemplo n.º 6
0
int bopen(char *nom)
{
	HMMIO fp;
	int r=0;
	char nom2[200];

	r=nextfile();
	if (r)
	{
		verifnom(nom,nom2);
		fp = mmioOpen(nom2,NULL,MMIO_READ);
		if (fp) { ftab[r-1]=fp; fused[r-1]=1; }
		else r=0;
	}
	return(r);
}
Ejemplo n.º 7
0
Archivo: n1.c Proyecto: 99years/plan9
void casenx(void)
{
	lgf++;
	skip();
	getname();
	nx++;
	if (nmfi > 0)
		nmfi--;
	strcpy(mfiles[nmfi], nextf);
	nextfile();
	nlflg++;
	ip = 0;
	pendt = 0;
	frame = stk;
	nxf = frame + 1;
}
Ejemplo n.º 8
0
Cell *jump(Node **a, int n)	/* break, continue, next, nextfile, return */
{
	Cell *y;

	switch (n) {
	case EXIT:
		if (a[0] != NULL) {
			y = execute(a[0]);
			errorflag = getfval(y);
			tempfree(y);
		}
		longjmp(env, 1);
	case RETURN:
		if (a[0] != NULL) {
			y = execute(a[0]);
			if ((y->tval & (STR|NUM)) == (STR|NUM)) {
				setsval(fp->retval, getsval(y));
				fp->retval->fval = getfval(y);
				fp->retval->tval |= NUM;
			}
			else if (y->tval & STR)
				setsval(fp->retval, getsval(y));
			else if (y->tval & NUM)
				setfval(fp->retval, getfval(y));
			else		/* can't happen */
				ERROR "bad type variable %d", y->tval FATAL;
			tempfree(y);
		}
		return(jret);
	case NEXT:
		return(jnext);
	case NEXTFILE:
		nextfile();
		return(jnextfile);
	case BREAK:
		return(jbreak);
	case CONTINUE:
		return(jcont);
	default:	/* can't happen */
		ERROR "illegal jump type %d", n FATAL;
	}
	return 0;	/* not reached */
}
Ejemplo n.º 9
0
/* in  : cnct	コネクタ No.(0 or 1)
	 slot	スロット No.(通常 0、マルチタップ 0〜3)
   out : 0〜15	使用ファイル数
*/
int GetCardEntry(int cnct, int slot)
{
	long i = 0;
	char key[32];
	struct DIRENTRY *d;

	sprintf(key, "bu%1d%1d:*", cnct, slot);	/* cnct:コネクタ番号 */
						/* slot:スロット番号 */
	d = SLOT_DIR;
	if(firstfile(key, d) == d)	/* d:バッファポインタ */
	{
		do {
			i++;
			d++;
		} while(nextfile(d) == d);
	}

	return i;			/* 使用ファイル数 */
}
Ejemplo n.º 10
0
void
main(int argc, char *argv[])
{
	Reprog *exp;
	char *pattern = 0;
	int n = 1000;
	char *line;
	int xflag = 0;
	int iflag = 0;
	Biobuf bin;
	Biobuf *b = &bin;
	char buf[256];

	ARGBEGIN {
	case 'l':
	case 'n':
		n=atoi(EARGF(usage()));
		break;
	case 'e':
		pattern = strdup(EARGF(usage()));
		break;
	case 'f':
		stem = strdup(EARGF(usage()));
		break;
	case 's':
		suffix = strdup(EARGF(usage()));
		break;
	case 'x':
		xflag++;
		break;
	case 'i':
		iflag++;
		break;
	default:
		usage();
		break;

	} ARGEND;

	if(argc < 0 || argc > 1)
		usage();

	if(argc != 0) {
		b = Bopen(argv[0], OREAD);
		if(b == nil) {
			fprint(2, "split: can't open %s: %r\n", argv[0]);
			exits("open");
		}
	} else
		Binit(b, 0, OREAD);

	if(pattern) {
		Resub match[2];

		if(!(exp = regcomp(iflag? fold(pattern, strlen(pattern)):
		    pattern)))
			badexp();
		memset(match, 0, sizeof match);
		matchfile(match);
		while((line=Brdline(b,'\n')) != 0) {
			memset(match, 0, sizeof match);
			line[Blinelen(b)-1] = 0;
			if(regexec(exp, iflag? fold(line, Blinelen(b)-1): line,
			    match, 2)) {
				if(matchfile(match) && xflag)
					continue;
			} else if(output == 0)
				nextfile();	/* at most once */
			Bwrite(output, line, Blinelen(b)-1);
			Bputc(output, '\n');
		}
	} else {
		int linecnt = n;

		while((line=Brdline(b,'\n')) != 0) {
			if(++linecnt > n) {
				nextfile();
				linecnt = 1;
			}
			Bwrite(output, line, Blinelen(b));
		}

		/*
		 * in case we didn't end with a newline, tack whatever's 
		 * left onto the last file
		 */
		while((n = Bread(b, buf, sizeof(buf))) > 0)
			Bwrite(output, buf, n);
	}
	if(b != nil)
		Bterm(b);
	exits(0);
}
Ejemplo n.º 11
0
/** @brief
 *
 * @param args contains the parsed cmd-line options & arguments.
 * @param argc number of cmd-line arguments.
 * @param argv list of cmd-line arguments
 * @param optind index of the first non-option cmd-line argument.
 *
 * @return exit status for main() to return.
 */
int filterkeys(struct cmdargs *args, int argc, char *argv[], int optind) {
  FILE *ffile, *outfile;
  dbfr_t *filter_reader, *stream_reader;
  char *t_keybuf;
  int i, acum_len;

  if (args->outfile) {
    if ((outfile = fopen(args->outfile, "w")) == NULL) {
      perror(args->outfile);
      exit(EXIT_FILE_ERR);
    }
  } else {
    outfile = stdout;
  }

  /* choose field delimiter */
  if (!(delim = (args->delim ? args->delim : getenv("DELIMITER"))))
    delim = default_delim;
  expand_chars(delim);
  delim_len = strlen(delim);

  /* get the filter file */
  int fd = open64(args->filter_file, O_RDONLY);
  if (fd != -1) {
    ffile = fdopen(fd, "r");
  } else {
    if (!strcmp(args->filter_file, "-")) {
      ffile = stdin;
    } else {
      warn("Opening filter file %s", args->filter_file);
      return EXIT_FILE_ERR;
    }
  }
  filter_reader = dbfr_init( ffile );

  /* input files */
  if (!(ffile = (optind < argc ? nextfile(argc, argv, &optind, "r") : stdin)))
    return EXIT_FILE_ERR;
  stream_reader = dbfr_init( ffile );


  if (configure_filterkeys(&fk_conf, args, filter_reader, stream_reader) != 0) {
    fprintf(stderr, "%s: error setting up configuration.\n", argv[0]);
    return EXIT_HELP;
  }

  load_filter(&fk_conf, filter_reader);
  dbfr_close( filter_reader );

  if (args->preserve_header) {
    /* if indexes where supplied read the header */
    if (args->akeys && args->bkeys)
      dbfr_getline(stream_reader);
    fputs(stream_reader->current_line, outfile);
  }

  t_keybuf = (char *) xmalloc(fk_conf.key_buffer_sz);
  while (ffile) {
    while (dbfr_getline(stream_reader) > 0) {

      for (acum_len = 0, i = 0;
           i < fk_conf.key_count && fk_conf.key_buffer_sz > acum_len;
           i++) {
        acum_len += get_line_field(t_keybuf + acum_len,
                                   stream_reader->current_line,
                                   fk_conf.key_buffer_sz - acum_len,
                                   fk_conf.bindexes[i], delim);
        if (i != fk_conf.key_count -1) {
          strcat(t_keybuf + acum_len, delim);
          acum_len += delim_len;
        }
      }

      if (acum_len > 0) {
        int found = (ht_get(&fk_conf.filter, t_keybuf) ==
                     (void*) 0xDEADBEEF ? 1 : 0);
        if (found ^ args->invert)
          fputs(stream_reader->current_line, outfile);
      }
    }

    dbfr_close(stream_reader);
    if ((ffile = nextfile(argc, argv, &optind, "r"))) {
      stream_reader = dbfr_init( ffile );
      /* reconfigure fields (needed if labels were used) */
      /* TODO(rgranata): implement reconfigure field
      if (reconfigure_filterkeys(&fk_conf, args, NULL, stream_reader) != 0) {
        fprintf(stderr, "%s: error parsing field arguments.\n", argv[0]);
        return EXIT_HELP;
      }
      */
      if (args->preserve_header)
        dbfr_getline(stream_reader);
    }
  }
  if (t_keybuf)
    free(t_keybuf);

  ht_destroy(&fk_conf.filter);

  return 0;
}
Ejemplo n.º 12
0
Archivo: n1.c Proyecto: 99years/plan9
Tchar getch0(void)
{
	Tchar i;

again:
	if (pbp > lastpbp)
		i = *--pbp;
	else if (ip) {
		/* i = rbf(); */
		i = rbf0(ip);
		if (i == 0)
			i = rbf();
		else {
			++ip;
			if (pastend(ip)) {
				--ip;
				rbf();
			}
		}
	} else {
		if (donef || ndone)
			done(0);
		if (nx || 1) {	/* BUG: was ibufp >= eibuf, so EOF test is wrong */
			if (nfo < 0)
				ERROR "in getch0, nfo = %d", nfo WARN;
			if (nfo == 0) {
g0:
				if (nextfile()) {
					if (ip)
						goto again;
				}
			}
			nx = 0;
#ifdef UNICODE
			if (MB_CUR_MAX > 1)
				i = get1ch(ifile);
			else
#endif	/*UNICODE*/
				i = getc(ifile);
			if (i == EOF)
				goto g0;
			if (ip)
				goto again;
		}
		if (i >= 040)			/* zapped: && i < 0177 */
			goto g4;
		i = ifilt[i];
	}
	if (cbits(i) == IMP && !raw)
		goto again;
	if (i == 0 && !init && !raw) {		/* zapped:  || i == 0177 */
		goto again;
	}
g4:
	if (ismot(i))
		return i;
	if (copyf == 0 && sfbits(i) == 0)
		i |= chbits;
	if (cbits(i) == eschar && !raw)
		setcbits(i, ESC);
	return(i);
}
Ejemplo n.º 13
0
LRESULT CALLBACK EditProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){

    char bstr[MAX_PATH];
    char *p,c;
    int i,k,n,o,r,f;
    POINT pt;
    struct edvars *ev;

    r = 0;

    //if (domove(GetParent(hwnd),message,wParam,lParam)) return 0;

    switch (message) {
    case WM_COPYDATA:
        if (0x4F4E4242 == ((PCOPYDATASTRUCT)lParam)->dwData)
        {
            char buff[MAX_PATH];
            int line_nr;
            const char *file = (const char*)((PCOPYDATASTRUCT)lParam)->lpData;
            getfile(buff, file, &line_nr);
            set_currentdir(buff);
            LoadFile(buff);
            if (line_nr) {
                ed_cmd(EK_GOTOLINE,line_nr-1);
                //ed_cmd(EK_MARK,lpos,imin(lpos+1,nextline(lpos,1)));
            }

            r = TRUE;
            goto p0r;
        }

        return bbn_receive_data(hwnd, lParam);

    default:
        if (bb_broadcast_msg == message && message)
        {
            if (bb_register(hwnd) && bb_getstyle(hwnd))
               goto reconfig1;
            return 0;
        }
        break;

    case BB_RECONFIGURE:
        if (bb_getstyle(hwnd))
            goto reconfig1;
        return 0;


    reconfig1:
        bb_close_dlg();
        makedlgfont();

    reconfig:
        zy0 = title_h + FRM-1;
        setsize(hwnd);
        new_back();
        InvalidateRect(hwnd, NULL, FALSE);
        return 0;

    case BB_SETSTYLESTRUCT:
    {
        StyleStruct *d = (StyleStruct *)wParam;
        StyleStruct *s = (StyleStruct *)lParam;
        memset(d, 0, sizeof *d);
        memcpy(d, s, sizeof *d);
        break;
    }

    case BB_SETSTYLE:
    {
        char *d = (char *)wParam;
        char *s = (char *)lParam;
        strcpy(d, s);
        break;
    }

    case WM_CREATE:
        zy0 = title_h + FRM-1;
        setsize(ewnd=hwnd);
        dragC  = LoadCursor(hInst,MAKEINTRESOURCE(101));
        dragCp = LoadCursor(hInst,MAKEINTRESOURCE(102));
        pointC = hCurs = LoadCursor(NULL,IDC_ARROW);
        init_edit(hwnd);
        DragAcceptFiles(hwnd,TRUE);
        if (false == bb_register(hwnd) || false == bb_getstyle(hwnd))
            readstyle(defstyle);
        goto reconfig1;


    case WM_DROPFILES: {
        POINT pt;
        HDROP hDrop = (HDROP)wParam; int n,f;
        ev=edp;
        f=0;

        GetCursorPos(&pt);
        if (GetAsyncKeyState(VK_CONTROL)<0) f=1;
        if (GetAsyncKeyState(VK_SHIFT)<0)   f=2;
        if (f) ScreenToClient(hwnd,&pt);

        for (i=-1, k=0; i<k; i++)
        {
            n=DragQueryFile (hDrop, i, p=bstr, 255);
            if (i<0)
            {
                k=n;
            }
            else
            if (f==0)
            {
                LoadFile(p);
            }
            else
            if (f==2)
            {
                if (readstyle(p))
                {
                    CopyFile(p, defstyle, FALSE);
                }
                break;
            }
            else
            {
                if (i == 0 && -1 == getmoupos(pt.x ,pt.y))
                    break;

                ed_cmd(EK_SETVAR);
                ed_cmd(EK_INSERT, p);
                ed_cmd(KEY_RET);
            }
        }
        DragFinish(hDrop);
        SetForegroundWindow(hwnd);
        if (f==0) goto showf;
        if (f==2) goto reconfig1;
        goto p0;
        }

    case WM_QUERYENDSESSION:
        return (1 == QueryDiscard(hwnd,1));

    case WM_ENDSESSION:
    {
        //void savecfg(void); savecfg();
        return 0;
    }

    case WM_DESTROY:
        exit_edit();
        DragAcceptFiles(hwnd,FALSE);
        bb_unregister(hwnd);
        PostQuitMessage(0);
        return 0 ;


    case WM_ACTIVATE:
        i=LOWORD(wParam);
        if (i==WA_ACTIVE)
            clickflag=0;

        return 0;

    case WM_ACTIVATEAPP:
        if (wParam) {
            clickflag=2;
        }
        return 0;

    case WM_LBUTTONDOWN:
    case WM_RBUTTONDOWN:
        if (alt_f) alt_f=2;

    case WM_MOUSEMOVE:
#if 0
    {
        static int wm;
        i = (short)HIWORD(lParam)/2;
        n = wm;
        wm = i;
        wParam = MAKELPARAM(0,(n-i)*30);
        goto mwhl;

    }
#endif
    case WM_LBUTTONDBLCLK:
    case WM_LBUTTONUP:
    case WM_RBUTTONUP:
    case WM_MBUTTONUP:
    case WM_MBUTTONDOWN:

        if (drag==0 && domove (hwnd, message, wParam, lParam))
            return 0;

        do_mouse(hwnd, wParam, lParam, message);

        if (message==WM_MOUSEMOVE && 0==(wParam & (MK_LBUTTON | MK_RBUTTON)))
            return 0;

        goto p0;

    case WM_TIMER:

        if (wParam==2) {
            resetmsg(hwnd);
            goto p0;
        }

        if (wParam==4) {
            mousewheelaccu=0;
        t0:
            KillTimer(hwnd, wParam);
            return 0;
        }

        GetCursorPos(&pt);
        ScreenToClient(hwnd,&pt);
        o=getmoupos(pt.x ,pt.y);
        if (o!=tcmd) {
            settimer(hwnd, o, SCROLL_INTERVAL);
            return 0;
        }

        if (tcmd==0) goto t0;
        c=ltup; ltup=0;
        ed_cmd(tcmd);
        ed_cmd(tcmd);
        upd=1;
        ltup=c;
        k=GetAsyncKeyState(VK_SHIFT)&0x8000;
        domarking(k!=0 || (0==moumrk && 0==drag));
        goto p0;


    case WM_SIZE:
        if (SIZE_MINIMIZED == wParam)
            return 0;

        if (edp) upd=1;
        ed_cmd(EK_SIZE);
        new_back();

    case WM_MOVE:
        setsize(hwnd);
        goto p0;

/*
   case WM_WINDOWPOSCHANGED:
        ewx0 = ((LPWINDOWPOS) lParam)->x;
        ewy0 = ((LPWINDOWPOS) lParam)->y;
        ewxl = ((LPWINDOWPOS) lParam)->cx;
        ewyl = ((LPWINDOWPOS) lParam)->cy;
        cfg_f |= 1;
        break; //process wm_move/wm_size

    case WM_WINDOWPOSCHANGING:
        SnapWindowToEdge((WINDOWPOS*)lParam, 10, 0);
        setsize(hwnd);
        return 0;
*/

    case WM_VSCROLL:
        vscroll(wParam);
        goto p0;

    case WM_HSCROLL:
        hscroll(wParam);
        goto p0;

    case WM_SETFOCUS:
        k_alt = 0>GetAsyncKeyState(VK_MENU);
        k_shft= 0>GetAsyncKeyState(VK_SHIFT);
        k_ctrl= 0>GetAsyncKeyState(VK_CONTROL);
        CreateCaret(hwnd,NULL,My_CaretSize,zy);
        caret=1;
        checkftime(hwnd);
        goto f1;

    case WM_KILLFOCUS:
        DestroyCaret();
        caret=0;
    f1:
        if (edp) upd=1;
        goto p0;

p0:
        r=0;
p0r:
        set_update(hwnd);
        return r;


    case WM_ERASEBKGND:
        return 1;

    case WM_PAINT:
        paint_window (hwnd);
        return 0;


    case WM_COMMAND:
        switch (LOWORD(wParam)) {

        case CMD_HELP:
#if 0
            bbnote_help();
            return 0;
#else
            if (fileexist(set_my_path(bstr, "bbnote.txt")))
                LoadFile(bstr);
            else if (fileexist(set_my_path(bstr, "docs/bbnote.txt")))
                LoadFile(bstr);
            goto p0;
#endif


        case CMD_EXIT:
            goto quit;

        case CMD_MENU_2:
        filemenu:
            if (ed0)
            {
                struct edvars *e = ed0;
                struct strl   *s = NULL;
                while (e)
                {
                    char temp[MAX_PATH];
                    sprintf(temp, "&%s", fname(e->sfilename));
                    appendstr(&s, temp);
                    e = e->next;
                }
                bb_file_menu (hwnd, lParam, s);
            }
            return 0;

        case CMD_MENU_1:
            bb_menu(hwnd, lParam);
            return 0;

        case CMD_COLOR:
            goto reconfig;

        case CMD_UPD:
            settitle();
            if (edp) upd=1;
            goto p0;


        case CMD_ZOOM:
    zoom:
            ShowWindow(hwnd, IsZoomed(hwnd) ? SW_SHOWNORMAL : SW_MAXIMIZE);
            return 0;

        case CMD_SEARCH:
        search:
            if (edp) bb_search_dialog(hwnd);
            return 0;

        case CMD_CLOSE:
        closefile:
            if (edp)
            {
                if (1 != QueryDiscard_1(hwnd, 1)) goto p0;
                if (ed0->next==NULL)
                {
                    extern HWND mwnd;
                    SendMessage(mwnd, WM_KEYDOWN, VK_ESCAPE, 0);
                    //DestroyWindow(mwnd);
                }
                CloseFile();
            }
            goto p0;

        case CMD_OPEN:
        openfile:
            ev=edp;
            DoFileOpenSave(hwnd, 0);
showf:
            if (ev==NULL || ev->next)
            {
                edp = ev ? ev->next : ed0;
                settitle();
            }
            goto p0;

        case CMD_RELOAD:
        reload:
            if (edp) f_reload(1);
            goto p0;


        case CMD_LIST:
            lParam = 2;
            goto filemenu;

        case CMD_NEW:
        newfile:
            NewFile();
            goto p0;

        case CMD_SAVE:
        savefile:
            if (edp) DoFileOpenSave(hwnd, 2);
            goto p0;

        case CMD_SAVEAS:
            if (edp!=NULL) DoFileOpenSave(hwnd, 1);
            break;

        case CMD_SAVEALL:
        //saveall:
            return QueryDiscard(hwnd, 0);

        case CMD_UNDO:
            ed_cmd(KEY_C_Z);
            goto p0;

        case CMD_REDO:
            ed_cmd(KEY_CS_Z);
            goto p0;

        case CMD_ABOUT:
            oyncan_msgbox(
              VERSION_STRING
              "\n"
              "\nediting with style"
              "\n04/2003 by grischka"
              "\n"
              "\[email protected]"
              , NULL, 1);
              return 0;


        case CMD_OPTIONS:
            goto config;

        case CMD_INFO:
            resetmsg(hwnd);
            p=(char*)lParam;
            if (p[0]==1) p++;
            else infoflg=1,infotimer=SetTimer(hwnd,2,666,NULL);
            strcpy(infomsg,p);
            if (edp) upd=1;
            goto p0;


        case CMD_FILECHG:
        {
            struct edvars *p=edp;
            edp=(struct edvars*)lParam;
            settitle();
            set_update(hwnd);
            f_reload(0);
            edp=p;
            settitle();
            goto p0;
        }

        default:
            i = LOWORD(wParam);
            if (i>=CMD_FILE && i< CMD_FILE_M)
            {
                struct edvars *p=ed0;
                i-=CMD_FILE;
                for (;i && p!=NULL; p=p->next,i--);
                if (p) {
                    //edp = p; settitle();
                    insfile(p);
                    goto p0;
                }
                return 0;
            }
            break;

        }
        break;

quit:
    if (1 == QueryDiscard(hwnd, 1))
        DestroyWindow(hwnd);
    return 0;

    case WM_SYSKEYDOWN:
        f=3; goto k1;

    case WM_SYSKEYUP:
        f=2; goto k1;

    case WM_KEYUP:
        if (wParam==VK_CONTROL && drag==3)  setdragc(2);
        f=0; goto k1;

    case WM_KEYDOWN:
        if (wParam==VK_CONTROL && drag==2)  setdragc(3);
        if (wParam==VK_SCROLL) { scroll_lock^=1; goto p0; }

        f=1; k1:

        n=LOWORD(wParam);

#if 0
        sprintf(bstr,"key %d  stat %d",n,f);
        if (n!=VK_MENU) MessageBox(NULL, bstr, "", MB_OK|MB_TOPMOST|MB_SETFOREGROUND);
#endif
        n=trans_keys(n, f);
        //if (0==n) goto p0;
        if (0==n) return 0;

        if (n>=2110 && n<=2117) {
        vmark=k_alt!=0;
        domarking(1);
        ed_cmd(n-100);
        domarking(1);
        goto p0;
        }

        switch (n) {

        case KEY_F8: return 0;
        case KEY_A_RIGHT:
        case KEY_F6:   nextfile(); goto p0;
        case KEY_A_LEFT:
        case KEY_C_F6: prevfile(); goto p0;

        case KEY_F10:  goto zoom;
        case KEY_F3:
        case KEY_C_F:  goto search;
        case KEY_C_F4: goto closefile;
        case KEY_C_O:  goto openfile;
        //case KEY_A_F3: goto reload;
        case KEY_C_N:  goto newfile;
        case KEY_C_L:  lParam = 0; goto filemenu;

        case KEY_F4:
            QueryDiscard(hwnd, 0);
            bb_reconfig();
            return 0;

        case KEY_S_F4:
            if (IDOK == oyncan_msgbox("Do you want to write all files?", "", 1+8))
                QueryDiscard(hwnd, 4);
            return 0;


        case KEY_C_S:  goto savefile;
        case KEY_A_F4: goto quit;

        case KEY_A_F2:
config:
            n = tabs;
            bb_config_dialog(hwnd);
            if (n!=tabs) goto reload;
            return 0;

        case KEY_ESC:
            if (drag==0) goto quit;
            dragmove=0;
            do_mouse(hwnd, 0,0,WM_LBUTTONUP);
            goto p0;

        case KEY_UP:
        case KEY_DOWN:
            if (scroll_lock) n+=200;
            goto defkey;

        case KEY_LEFT:
        case KEY_RIGHT:
            if (scroll_lock) n=(n^1)+204;
            goto defkey;
        }

    defkey:
        domarking(0);
        ed_cmd(n);
        i=n;
        if (i!=KEY_C_A
         && i!=KEY_C_U
         && i!=KEY_C_7
         && i!=KEY_C_8
         && i!=KEY_C_9
         && i!=KEY_C_0
         && i!=KEY_TAB
         && i!=KEY_S_TAB
         )
            unmark();
        goto p0;


    case WM_MOUSEWHEEL:
        i = mousewheelaccu + mousewheelfac * (short)HIWORD(wParam);
        while (i < -300)
            ed_cmd(KEY_C_DOWN), i+=600;
        while (i >  300)
            ed_cmd(KEY_C_UP),   i-=600;

        mousewheelaccu=i;
        unmark();
        SetTimer(hwnd, 4, 200, NULL);
        goto p0;


    case WM_NCPAINT:
        return 0;


    case WM_CHAR:
        n = LOWORD(wParam);
        if (n<32||n==127) return 0;

        resetmsg(hwnd);
        ed_cmd(EK_CHAR, n);
        goto p0;



    case CMD_GOTOLINE:
        ed_cmd(EK_GOTOLINE,wParam-1);
        ed_cmd(EK_MARK,lpos,imin(lpos+1,nextline(lpos,1)));
        lmf=2;
        goto p0;

    case CMD_LOADFILE:
        r=LoadFile((char*)wParam);
        goto p0r;

    case CMD_NSEARCH:
        resetmsg(hwnd);
        if (wParam&8) {
            ed_cmd(EK_REPLACE,(char *)lParam);
            if (wParam&1)
               ed_cmd(EK_GOTO,fpos+strlen((char*)lParam));
            goto p0;
        }
        unmark();
        if (wParam!=0) {
            struct sea *s=(struct sea *)lParam;
            struct edvars *ev0;

            for (ev0=edp;;) {
                r=ed_search(s);
                if (r || 0==(s->sf&128)) break;
                s->sf &= ~4;
                if (s->sf & 1) {
                    if (edp->next==NULL) break;
                    nextfile();
                    s->from=0;
                    continue;
                }
                if (s->sf & 2) {
                    if (edp==ed0) break;
                    prevfile();
                    s->from=flen;
                    continue;
                }}
            if (r<=0) {
                edp=ev0;
                settitle();
            } else {
               ed_cmd(KEY_HOME);
               ed_cmd(EK_MARK,s->a,s->e);
               ed_cmd(EK_GOTO,s->a);
            }
        }
        goto p0r;

    }
    return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Ejemplo n.º 14
0
/** @brief  
  * 
  * @param args contains the parsed cmd-line options & arguments.
  * @param argc number of cmd-line arguments.
  * @param argv list of cmd-line arguments
  * @param optind index of the first non-option cmd-line argument.
  * 
  * @return exit status for main() to return.
  */
int funiq(struct cmdargs *args, int argc, char *argv[], int optind) {

  char delim[] = { 0xfe, 0x00 };  /* the delimiter */
  int *fields = NULL;   /* array of field indexes */
  size_t fields_sz = 0; /* the size of the array */
  size_t n_fields;      /* the number of things in the array */

  FILE *in = NULL;
  dbfr_t *in_reader = NULL;

  char **prev_line;             /* fields from previous line of input */
  char cur_field[FIELD_LEN_LIMIT];

  int i;

  int dup_count = 1;            /* used with -c option */
  char linebreak[3];

  /* use the default delimiter if necessary */
  if (!args->delim) {
    args->delim = getenv("DELIMITER");
    if (!args->delim)
      args->delim = delim;
  }
  expand_chars(args->delim);

  /* Get the first file, skipping any 0-byte files. */
  if (optind < argc) {
    do {
      in = nextfile(argc, argv, &optind, "r");
      if (in)
        in_reader = dbfr_init(in);
    } while (in && in_reader->eof);
  } else {
    in = stdin;
    in_reader = dbfr_init(in);
  }

  if (!in && !in_reader) {
    fprintf(stderr, "%s: no valid input files\n", argv[0]);
    return EXIT_HELP;
  }

  if (in_reader->eof) {
    /* There were valid input files, but they were all empty. */
    return EXIT_OKAY;
  }

  if (args->fields)
    n_fields = expand_nums(args->fields, &fields, &fields_sz);
  else if (args->field_labels)
    n_fields = expand_label_list(args->field_labels, in_reader->next_line,
                                 args->delim, &fields, &fields_sz);
  if (n_fields < 0) {
    fprintf(stderr, "%s: error expanding field list\n", argv[0]);
    return EXIT_HELP;
  }

  /* prepare the array of previous field values */
  prev_line = xmalloc(sizeof(char *) * n_fields);
  for (i = 0; i < n_fields; i++) {
    prev_line[i] = xmalloc(sizeof(char *) * FIELD_LEN_LIMIT);
  }

  /* get the first line to seed the prev_line array */
  i = dbfr_getline(in_reader);

  /* preserve input linebreak style.  assume there can only be 1 or 2 chars
   * in a linebreak sequence */
  if (in_reader->current_line[i - 2] == '\r' ||
      in_reader->current_line[i - 2] == '\n') {
    linebreak[0] = in_reader->current_line[i - 2];
    linebreak[1] = in_reader->current_line[i - 1];
    linebreak[2] = '\0';
  } else {
    linebreak[0] = in_reader->current_line[i - 1];
    linebreak[1] = '\0';
  }
  chomp(in_reader->current_line);

  for (i = 0; i < n_fields; i++) {
    get_line_field(prev_line[i], in_reader->current_line, FIELD_LEN_LIMIT - 1,
                   fields[i] - 1, args->delim);
  }
  printf("%s", in_reader->current_line); /* first line is never a dup */

  while (in) {
    int matching_fields;

    while (dbfr_getline(in_reader) > 0) {
      chomp(in_reader->current_line);

      matching_fields = 0;

      for (i = 0; i < n_fields; i++) {
        /* extract the field from the input line */
        get_line_field(cur_field, in_reader->current_line, FIELD_LEN_LIMIT - 1,
                       fields[i] - 1, args->delim);

        /* see if the field is a duplicate */
        if (str_eq(cur_field, prev_line[i]))
          matching_fields++;

        /* store this line's value */
        strcpy(prev_line[i], cur_field);
      }

      /* if not all of the fields matched, the line
         wasn't a duplicate */
      if (matching_fields != n_fields) {

        if (args->count) {
          /* print the number of dups for
           * the previous output line */
          printf("%s%d%s", args->delim, dup_count, linebreak);
        } else {
          /* give the previous output line a linebreak */
          printf("%s", linebreak);
        }
        printf("%s", in_reader->current_line);
        dup_count = 1;
      } else {
        dup_count++;
      }
    }

    dbfr_close(in_reader);
    in = nextfile(argc, argv, &optind, "r");
    if (in)
      in_reader = dbfr_init(in);
  }

  if (args->count) {
    /* print the number of dups for the last output line */
    printf("%s%d%s", args->delim, dup_count, linebreak);
  } else {
    /* give the last output line a linebreak */
    printf("%s", linebreak);
  }

  for (i = 0; i < n_fields; i++) {
    free(prev_line[i]);
  }
  free(prev_line);
  free(fields);
  return EXIT_OKAY;
}
Ejemplo n.º 15
0
/** @brief  
  * 
  * @param args contains the parsed cmd-line options & arguments.
  * @param argc number of cmd-line arguments.
  * @param argv list of cmd-line arguments
  * @param optind index of the first non-option cmd-line argument.
  * 
  * @return exit status for main() to return.
  */
int truncfield(struct cmdargs *args, int argc, char *argv[], int optind) {

  char default_delim[] = { 0xfe, 0x00 };
  FILE *in;
  dbfr_t *in_reader;
  int *field_list = NULL;       /* list of fields to remove */
  size_t field_list_sz = 0;

  size_t n_fields = 0;          /* the number of fields from input
                                   file */
  if (! args->fields && ! args->field_labels) {
    fprintf(stderr, "%s: -f or -F must be specified.\n", argv[0]);
    return EXIT_HELP;
  }
  if (args->output_fname) {
    if (!freopen(args->output_fname, "w", stdout)) {
      warn(args->output_fname);
      return EXIT_FILE_ERR;
    }
  } else if (args->append_fname) {
    if (!freopen(args->append_fname, "a", stdout)) {
      warn(args->append_fname);
      return EXIT_FILE_ERR;
    }
  }

  if (!args->delim) {
    args->delim = getenv("DELIMITER");
    if (!args->delim)
      args->delim = default_delim;
  }
  expand_chars(args->delim);

  if (optind < argc)
    in = nextfile(argc, argv, &optind, "r");
  else
    in = stdin;
  if (! in) {
    fprintf(stderr, "%s: no valid input files.\n", argv[0]);
    return EXIT_FILE_ERR;
  }
  in_reader = dbfr_init(in);

  if (args->fields) {
    field_list_sz = expand_nums(args->fields, &field_list, &field_list_sz);
  } else if (args->field_labels) {
    field_list_sz = expand_label_list(args->field_labels, in_reader->next_line,
                                      args->delim, &field_list, &field_list_sz);
  }
  if (field_list_sz < 1) {
    fprintf(stderr, "%s: error expanding field list.\n", argv[0]);
    return EXIT_HELP;
  }
  qsort(field_list, field_list_sz, sizeof(field_list[0]),
        (qsort_cmp_func_t) qsort_intcmp);

  while (in) {

    int next_field_to_trunc;    /* index into field_list */
    int i;                      /* index of current input field */
    int f_first, f_last;        /* position of first and last char
                                   in a field */
    int first_field_printed;    /* used to control delimiter output */

    while (dbfr_getline(in_reader) > 0) {
      next_field_to_trunc = 0;
      n_fields = fields_in_line(in_reader->current_line, args->delim);
      first_field_printed = 0;

      for (i = 0; i < n_fields; i++) {
        if (field_list[next_field_to_trunc] == i + 1) {
          ++next_field_to_trunc;
          if (i > 0)
            printf("%s", args->delim);
          first_field_printed = 1;
          continue;
        }
        if (!get_line_pos(in_reader->current_line, i, args->delim,
                          &f_first, &f_last))
          continue;

        if (first_field_printed)
          printf("%s", args->delim);

        printf("%.*s", f_last - f_first + 1,
               &(in_reader->current_line[f_first]));
        first_field_printed = 1;
      }

      /* print everything after the last field in the
       * line (preserves input line-break style) */
      get_line_pos(in_reader->current_line, n_fields - 1,
                   args->delim, &f_first, &f_last);
      printf("%s", &(in_reader->current_line[f_last + 1]));

    }
    dbfr_close(in_reader);
    in = nextfile(argc, argv, &optind, "r");
    if (in)
      in_reader = dbfr_init(in);
  }

  free(field_list);

  return EXIT_OKAY;
}
Ejemplo n.º 16
0
/** @brief Application entry point.
  *
  * @param args contains the parsed cmd-line options & arguments.
  * @param argc number of cmd-line arguments.
  * @param argv list of cmd-line arguments
  * @param optind index of the first non-option cmd-line argument.
  *
  * @return exit status for main() to return.
  */
int hashjoin (struct cmdargs *args, int argc, char *argv[], int optind) {
  hashtbl_t dimension;
  FILE *infile;
  dbfr_t *datareader;

  char *keybuffer = NULL;
  size_t keybuffer_sz = 0;

  char *value, *empty_value;
  size_t n_values, i;

  int *key_fields = NULL;
  size_t n_key_fields = 0;

  if (! args->key_labels &&
      ! (args->data_key_fields && args->dimension_key_fields)) {
    fprintf(stderr, "%s: missing key field argument(s)\n", getenv("_"));
    return EXIT_FAILURE;
  }

  if (! args->dimension_field_labels &&
      ! args->dimension_fields) {
    fprintf(stderr, "%s: missing dimension field argument\n", getenv("_"));
    return EXIT_FAILURE;
  }

  if (! args->delim) {
    args->delim = getenv("DELIMITER");
    if (! args->delim) {
      args->delim = default_delim;
    }
  }
  expand_chars(args->delim);
  if (! args->dimension_delim) {
    args->dimension_delim = args->delim;
  }

  ht_init(&dimension, 1024, NULL, NULL);
  n_values = hash_dimension_file(args, &dimension);

  empty_value = xmalloc(strlen(args->delim) * n_values);
  empty_value[0] = '\0';
  for (i = 0; i < n_values - 1; i++) {
    strcat(empty_value, args->delim);
  }

  if (argc > optind)
    infile = nextfile(argc, argv, &optind, "r");
  else
    infile = stdin;

  if (! args->key_labels) {
    n_key_fields = expand_nums(args->data_key_fields,
                               &key_fields, &n_key_fields);
    decrement(key_fields, n_key_fields);
  }

  while (infile) {
    datareader = dbfr_init(infile);

    if (args->key_labels) {
      n_key_fields = expand_label_list(args->key_labels, datareader->next_line,
                                       args->delim, &key_fields,
                                       &n_key_fields);
      decrement(key_fields, n_key_fields);
    }

    /* Add user-supplied dimension labels to the header row. */
    if (args->dimension_labels && ! args->dimension_field_labels) {
      dbfr_getline(datareader);
      chomp(datareader->current_line);
      printf("%s%s%s\n", datareader->current_line,
             args->delim, args->dimension_labels);
    }

    if (! keybuffer) {
      keybuffer = xmalloc(datareader->next_line_len);
      keybuffer_sz = datareader->next_line_len;
    }

    while (dbfr_getline(datareader) > 0) {
      if (datareader->current_line_len > keybuffer_sz) {
        keybuffer = xrealloc(keybuffer, datareader->current_line_len);
        keybuffer_sz = datareader->current_line_len;
      }
      chomp(datareader->current_line);
      extract_fields(key_fields, n_key_fields, datareader->current_line,
                     keybuffer, keybuffer_sz,
                     args->delim, args->delim);

      value = ht_get(&dimension, keybuffer);
      if (! value)
        value = empty_value;
      printf("%s%s%s\n", datareader->current_line, args->delim, value);
    }

    infile = nextfile(argc, argv, &optind, "r");
  }

  return EXIT_OKAY;
}
Ejemplo n.º 17
0
void
do_nextfile()
{
	(void) nextfile(1);
	longjmp(filebuf, 1);
}
Ejemplo n.º 18
0
/** @brief  
  * 
  * @param args contains the parsed cmd-line options & arguments.
  * @param argc number of cmd-line arguments.
  * @param argv list of cmd-line arguments
  * @param optind index of the first non-option cmd-line argument.
  * 
  * @return exit status for main() to return.
  */
int pivot(struct cmdargs *args, int argc, char *argv[], int optind) {

  int i, j, tmplen;

  char default_delim[] = { 0xFE, 0x00 };

  hashtbl_t key_hash;           /* outer hash */
  hashtbl_t *pivot_hash;        /* pointer for inner hashes */

  struct pivot_conf conf;
  /* variables for keeping track of the unique pivot strings */
  hashtbl_t uniq_pivots;        /* set of all pivot strings */
  char **pivot_array;           /* list of all pivot keys */
  size_t n_key_strings;         /* number of distinct key strings */
  size_t n_pivot_keys;          /* number of distinct pivot field values */

  double *line_values;          /* array of values */

  char *keystr, *pivstr;        /* hash key strings */
  size_t keystr_sz, pivstr_sz;

  char **headers = NULL;        /* array of header labels */
  size_t n_headers = 0;         /* number of fields */

  char *fieldbuf = NULL;        /* to hold fields extracted from input */
  size_t fieldbuf_sz = 0;       /* size of field buffer */

  FILE *fin;                    /* input file */
  dbfr_t *in_reader;
  size_t max_line_sz = 0;

  char empty_string[] = "";

  if (!args->delim) {
    args->delim = getenv("DELIMITER");
    if (!args->delim)
      args->delim = default_delim;
  }
  expand_chars(args->delim);

  delim = args->delim;

  /* get first input file pointer - either trailing arg or stdin */
  if (optind == argc)
    fin = stdin;
  else
    fin = nextfile(argc, argv, &optind, "r");
  if (!fin) {
    fprintf(stderr, "%s: no valid input files specified.\n", argv[0]);
    return EXIT_FILE_ERR;
  }
  in_reader = dbfr_init(fin);

  /* set locale with values from the environment so strcoll()
     will work correctly. */
  setlocale(LC_ALL, "");
  setlocale(LC_COLLATE, "");

  memset(&conf, 0, sizeof(conf));
  if (configure_pivot(&conf, args, in_reader->next_line, delim) != 0) {
    fprintf(stderr, "%s: error parsing input field arguments.\n", argv[0]);
    return EXIT_HELP;
  }
  if (conf.n_pivots == 0 || conf.n_values == 0) {
    fprintf(stderr, "%s: -p/-P and -v/-A must be specified.\n", argv[0]);
    return EXIT_HELP;
  }

  /* TODO: get rid of this arbirary field length limitation */
  fieldbuf = xmalloc(MAX_FIELD_LEN);
  fieldbuf_sz = MAX_FIELD_LEN;

  /* extract headers from first line of input if necessary */
  if (args->keep_header) {

    if (dbfr_getline(in_reader) < 1) {
      fprintf(stderr, "%s: unexpected end of file.\n", argv[0]);
      return EXIT_FILE_ERR;
    }
    chomp(in_reader->current_line);
    n_headers = fields_in_line(in_reader->current_line, delim);
    headers = xmalloc(sizeof(char *) * n_headers);

    for (i = 0; i < n_headers; i++) {
      get_line_field(fieldbuf, in_reader->current_line, fieldbuf_sz - 1,
                     i, delim);
      headers[i] = xmalloc(sizeof(char *) * strlen(fieldbuf) + 1);
      strcpy(headers[i], fieldbuf);
    }

#ifdef CRUSH_DEBUG
    for (i = 0; i < n_headers; i++) {
      fprintf(stderr, "%s%s", headers[i], i < n_headers - 1 ? args->delim : "");
    }
    fprintf(stderr, "\n");
#endif
  }

  /* these two buffers will have enough capacity to hold the entire input line,
     unless there are no key fields specified, in which case keystr will just
     be set to an empty string.
   */
  keystr = pivstr = NULL;
  keystr_sz = pivstr_sz = 0;

  ht_init(&key_hash, KEY_HASH_SZ, NULL, free_hash);
  ht_init(&uniq_pivots, PIVOT_HASH_SZ, NULL, NULL);
  n_key_strings = 0;
  n_pivot_keys = 0;

  /* no keys specified?  set keystr to an empty string */
  if (!conf.n_keys) {
    keystr = empty_string;
  }

  while (fin != NULL) {

    while (dbfr_getline(in_reader) > 0) {
      int value_in_hash = 1;
      int pivot_in_hash = 1;

      chomp(in_reader->current_line);
      if (conf.n_keys) {
        /* this could validly return NULL if both sizes are 0 the first time thru,
           when keystr is still NULL, but that shouldn't happen */
        if (realloc_if_needed(&keystr, &keystr_sz,
                              in_reader->current_line_sz) == NULL) {
          fprintf(stderr, "%s: out of memory.\n", getenv("_"));
          break;
        }
      }

      if (conf.n_pivots) {
        if (realloc_if_needed(&pivstr, &pivstr_sz,
                              in_reader->current_line_sz) == NULL) {
          fprintf(stderr, "%s: out of memory.\n", getenv("_"));
          break;
        }
      }

      /* make key string from keys[] */
      if (conf.n_keys)
        extract_fields_to_string(in_reader->current_line, keystr, keystr_sz,
                                 conf.keys, conf.n_keys, delim);

      /* make key string from pivots[] */
      extract_fields_to_string(in_reader->current_line, pivstr, pivstr_sz,
                               conf.pivots, conf.n_pivots, delim);

#ifdef CRUSH_DEBUG
      if (n_keys)
        fprintf(stderr, "key string: %s\n", keystr);
      if (n_pivots)
        fprintf(stderr, "pivot string: %s\n", pivstr);
#endif

      /* get hashtable value */
      pivot_hash = (hashtbl_t *) ht_get(&key_hash, keystr);
      if (!pivot_hash) {
        pivot_hash = xmalloc(sizeof(hashtbl_t));
        ht_init(pivot_hash, PIVOT_HASH_SZ, NULL, free);
        pivot_in_hash = 0;
      }

      line_values = ht_get(pivot_hash, pivstr);
      if (!line_values) {
        line_values = xmalloc(sizeof(double) * conf.n_values);
        memset(line_values, 0, sizeof(double) * conf.n_values);
        value_in_hash = 0;
      }


      /* add in values */
      for (i = 0; i < conf.n_values; i++) {
        tmplen =
          get_line_field(fieldbuf, in_reader->current_line, fieldbuf_sz - 1,
                         conf.values[i], delim);
        if (tmplen > 0) {
          line_values[i] += atof(fieldbuf);

          /* remember the greatest input floating-point precision for each
           * field */
          tmplen = float_str_precision(fieldbuf);
          if (conf.value_precisions[i] < tmplen) {
#ifdef CRUSH_DEBUG
            fprintf(stderr, "setting precision to %d for field %d\n", tmplen,
                    i);
#endif
            conf.value_precisions[i] = tmplen;
          }
        }
      }

      /* store hashtable value */
      if (!value_in_hash)
        ht_put(pivot_hash, pivstr, line_values);

      if (!pivot_in_hash) {
        ht_put(&key_hash, keystr, pivot_hash);
      }

      /* store the pivot key string for later use */
      ht_put(&uniq_pivots, pivstr, (void *) 1);
    }

    if (in_reader->current_line_sz > max_line_sz)
      max_line_sz = in_reader->current_line_sz;

    dbfr_close(in_reader);
    fin = nextfile(argc, argv, &optind, "r");
    if (fin) {
      in_reader = dbfr_init(fin);
      /* reconfigure in case the fields are rearranged in the new file */
      if (configure_pivot(&conf, args, in_reader->next_line, delim) != 0) {
        fprintf(stderr, "%s: error parsing input field arguments.\n", argv[0]);
        return EXIT_HELP;
      }
      /* throw out headers from all files after the first. */
      if (args->keep_header)
        dbfr_getline(in_reader);
    }
  }

  n_key_strings = key_hash.nelems;
  n_pivot_keys = uniq_pivots.nelems;

  /* sort the collection of all pivot key strings */
  pivot_array = xmalloc(sizeof(char *) * n_pivot_keys);
  ht_keys(&uniq_pivots, pivot_array);
  qsort(pivot_array, n_pivot_keys, sizeof(char *),
        (int (*)(const void *, const void *)) key_strcmp);
#ifdef CRUSH_DEBUG
  fprintf(stderr, "sorted pivot strings:\n");
  for (i = 0; i < n_pivot_keys; i++) {
    fprintf(stderr, "\t%s\n", pivot_array[i]);
  }
#endif

  /* OUTPUT SECTION */

  /* print headers separate from data if necessary */
  if (args->keep_header) {
    char *pivot_label;

    /* assumption - the largest line of input has a greater length
       than the combined length of all pivot field values and a 3-char
       separator.  safe assumption?  probably not if every input field
       is used as a pivot field. */
    pivot_label = xmalloc(max_line_sz);

    if (conf.n_keys) {
      for (i = 0; i < conf.n_keys; i++)
        printf("%s%s", headers[conf.keys[i]], delim);
    }
    for (i = 0; i < n_pivot_keys; i++) {
      pivot_label[0] = 0x00;

      /* get the current pivot field values & build a label with them */
      for (j = 0; j < conf.n_pivots; j++) {
        get_line_field(fieldbuf, pivot_array[i], fieldbuf_sz - 1, j, delim);
        strcat(pivot_label, fieldbuf);
        if (j != conf.n_pivots - 1)
          strcat(pivot_label, " - ");
      }

      /* get the value field labels & print them with the pivot label */
      for (j = 0; j < conf.n_values; j++) {
        printf("%s: %s", pivot_label, headers[conf.values[j]]);
        if (j != conf.n_values - 1)
          fputs(delim, stdout);
      }
      /* TODO: segfault is happening around here */
      if (i != n_pivot_keys - 1)
        fputs(delim, stdout);

    }
    fputs("\n", stdout);

    free(pivot_label);

    /* free each header string - don't need them anymore */
    for (i = 0; i < n_headers; i++)
      free(headers[i]);
    free(headers);
  }


  {
    char **key_array;
    llist_node_t *key_node;
    llist_t *key_list;
    char *empty_value_string;

    /* construct string for empty value set.  this should be big enough for
       n_values worth of zeros (of the appropriate precision) and delimiters
       in between.  here we'll just guess that a precision of 8 is enough. */
    empty_value_string = xmalloc((sizeof(char) * conf.n_values * 8) +
                                 (strlen(delim) * conf.n_values));
    empty_value_string[0] = 0x00;
    for (i = 0; i < conf.n_values; i++) {
      sprintf(empty_value_string, "%s%.*f", empty_value_string,
              conf.value_precisions[i], 0.0F);
      if (i != conf.n_values - 1)
        strcat(empty_value_string, delim);
    }

    key_array = xmalloc(sizeof(char *) * n_key_strings);
    j = ht_keys(&key_hash, key_array);

    /* j now holds the number of distinct keys to be output */
    assert(j == n_key_strings);

    /* sort the keys */
    qsort(key_array, n_key_strings, sizeof(char *),
          (int (*)(const void *, const void *)) key_strcmp);

    /* loop through all key strings */
    for (i = 0; i < n_key_strings; i++) {
      int k;
      pivot_hash = ht_get(&key_hash, key_array[i]);

      if (n_key_strings > 0)
        printf("%s%s", key_array[i], delim);

      /* loop through all possible pivot-string inner hashtable keys */
      for (k = 0; k < n_pivot_keys; k++) {
        /* loop through all values */
        line_values = ht_get(pivot_hash, pivot_array[k]);
        if (!line_values)
          fputs(empty_value_string, stdout);
        else {
          for (j = 0; j < conf.n_values; j++) {
            printf("%.*f%s", conf.value_precisions[j], line_values[j],
                   j != conf.n_values - 1 ? delim : "");
          }
        }
        if (k != n_pivot_keys - 1)
          fputs(delim, stdout);
      }
      fputs("\n", stdout);

    }
    free(empty_value_string);
    free(key_array);
  }

  /* CLEANUP SECTION */
  ht_destroy(&key_hash);
  ht_destroy(&uniq_pivots);

  if (keystr && keystr != empty_string)
    free(keystr);
  if (pivstr)
    free(pivstr);
  if (pivot_array)
    free(pivot_array);
  if (fieldbuf)
    free(fieldbuf);

  return EXIT_OKAY;
}
Ejemplo n.º 19
0
static void split(const char *fn)
{
    FILE *fp, *op = NULL;
    long long bytes = bytecount, lines = linecount, n, m;
    char b[4096];
    int c;

    if (fn[0] == '-' && fn[1] == '\0')
	fp = stdin;
    else if ((fp = fopen(fn, "r")) == NULL) {
	fprintf(stderr, "cannot open input");
	exit(1);
    }

    if (linecount > 0) {
	if (pattern == NULL) {
	    while ((c = getc(fp)) != EOF) {
		if (lines >= linecount) {
		    lines = 0;
		    if (op)
			fclose(op);
		    op = nextfile();
		}
		putc(c, op);
		if (c == '\n')
		    lines++;
	    }
	} else {
	    /* process line by line and only count lines
	       matching the pattern */
	    if (re_comp(pattern) != NULL)
		usage();
	    while (fgets(b, 4096, fp) != NULL) {
		/* does the line match? */
		if (re_exec(b))
		    lines++;
		if (lines >= linecount) {
		    lines = 0;
		    if (op)
			fclose(op);
		    op = nextfile();
		}
		fputs(b, op);
	    }
	}
    } else {
	do {
	    if ((n = bytecount - bytes) > sizeof b)
		n = sizeof b;
	    else if (n == 0 && (n = bytecount) > sizeof b)
		n = sizeof b;
	    m = fread(b, 1, n, fp);
	    if (bytes >= bytecount) {
		bytes = 0;
		if (op)
		    fclose(op);
		op = nextfile();
	    }
	    if (m) {
		fwrite(b, 1, m, op);
		bytes += m;
	    }
	}
	while (m);
    }
}