示例#1
0
TEST(search, lfind_lsearch) {
  int xs[10];
  memset(xs, 0, sizeof(xs));
  size_t x_size = 0;

  int needle;

  // lfind(3) can't find '2' in the empty table.
  needle = 2;
  ASSERT_EQ(nullptr, lfind(&needle, xs, &x_size, sizeof(xs[0]), int_cmp));
  ASSERT_EQ(0U, x_size);

  // lsearch(3) will add it.
  ASSERT_EQ(&xs[0], lsearch(&needle, xs, &x_size, sizeof(xs[0]), int_cmp));
  ASSERT_EQ(2, xs[0]);
  ASSERT_EQ(1U, x_size);

  // And then lfind(3) can find it.
  ASSERT_EQ(&xs[0], lfind(&needle, xs, &x_size, sizeof(xs[0]), int_cmp));
  ASSERT_EQ(1U, x_size);

  // Inserting a duplicate does nothing (but returns the existing element).
  ASSERT_EQ(&xs[0], lsearch(&needle, xs, &x_size, sizeof(xs[0]), int_cmp));
  ASSERT_EQ(1U, x_size);
}
示例#2
0
int main(int argc, char **argv)
{
    /* Set up an integer array*/
    int arr[] = {1, 2, -100, 100, 200, 500};

    assert(lsearch(arr, sizeof(arr)/sizeof(int), 100) == 3);
    assert(lsearch(arr, sizeof(arr)/sizeof(int), 1) == 0);
    assert(lsearch(arr, sizeof(arr)/sizeof(int), 1000) == -1);

    return 0;
}
示例#3
0
int main()
{
	int arr[] = { 4, 3, 1, 5, 7, 8, 9, 2 };	
	int n = 8;
	int key = 8;
	int res = *(int*)lsearch(&key, arr, n, sizeof(int), &IntCmp);
	printf("%d\n", res);		
	key = 6;
	void *res2 = lsearch(&key, arr, n, sizeof(int), &IntCmp);
	if (NULL == res2) 
		printf("True!");	
	return 0;
}
int main() {
    int a[] = {3, 4, 5, 1, 9, 2, 0, 4, 5};
    int m, n = sizeof(a) / sizeof(int);
    for (m = 1; m < n; m <<= 1);
    m <<= 1;
    node *tree = (node *)calloc(m, sizeof(node));
    puts("build");
    PRA(a, n);
    build(tree, a, 0, n-1, 1);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++)
            a[j] += 1;
        // printf("(%d, %d)\n", 0, i);
        update(tree, a, 0, n-1, 1, 0, i, 1);
    }
    PRA(a, n);
    print_tree(tree, a, 0, n-1, 1);
    puts("query");
    int v;
    for (int i = 0; i < n; i++) {
        v = query(tree, a, 0, n-1, 1, 0, i);
        printf("(%d, %d): %d\n", 0, i, v);
    }
    for (int i = 0; i < n; i++) {
        v = query(tree, a, 0, n-1, 1, i, n-1);
        printf("(%d, %d): %d\n", i, n-1, v);
        assert(v == lsearch(a, i, n-1));
    }
    
    return 0;
}
示例#5
0
int main(int argc, char const *argv[])
{
	int size = 5;
	int number = 3;

	// lsearch 线性查找
	int larr[] = {6, 4, 7, 3, 10};
	int *found = (int *)lsearch(&number, larr, 5, sizeof(int), intCmp);

	printf("%d\n", *found);

	// bsearch 二分查找
	int barr[] = {3, 4, 6, 7, 10};
	found = (int *)lsearch(&number, barr, 5, sizeof(int), intCmp);

	printf("%d\n", *found);

	return 0;
}
示例#6
0
int main() {
	int arr[] = { 1, 5, 16, 24, 36, 40, -7, 32768, 9, 115 };
	char names[][9] = { "John", "James", "Samantha", "Emily", "Georgio", "Nick", "Zac" };
	
	int find1 = 5, find2 = 63;
	char find3[5] = "Jack";
	char find4[9] = "Emily";
	// input to lsearch => address of thing to find, the array, the size of the array (important!), size of the element, a comparison function
	int* res1 = (int*) lsearch(&find1, arr, 10, sizeof(int), IntCmp);
	int* res2 = (int*) lsearch(&find2, arr, 10, sizeof(int), IntCmp);
	char* res3 = (char*) lsearch(&find3, names, 9, sizeof(*names), strcmp2);
	char* res4 = (char*) lsearch(&find4, names, 9, sizeof(*names), strcmp2);
	// res - arr gives the index at which the element was found (it wont be >= 0 if it's not found! (returns null, which means it's always less than an address))
	// bit different for char*, play around by changing jack to john etc.
	printf("Found 5: %d at %d\nFound 32768: %d\n", res1, res1 - arr, res2 - arr);
	printf("Jack found at %d %d\nSamantha found at %d %d\n", res3, (res3 - *names) / sizeof(*names), res4, (res4 - *names) / sizeof(*names));
	
	return 0;
}
示例#7
0
/*
 *  stress_lsearch()
 *	stress lsearch
 */
static int stress_lsearch(const args_t *args)
{
	int32_t *data, *root;
	size_t i, max;
	uint64_t lsearch_size = DEFAULT_LSEARCH_SIZE;

	if (!get_setting("lsearch-size", &lsearch_size)) {
		if (g_opt_flags & OPT_FLAGS_MAXIMIZE)
			lsearch_size = MAX_LSEARCH_SIZE;
		if (g_opt_flags & OPT_FLAGS_MINIMIZE)
			lsearch_size = MIN_LSEARCH_SIZE;
	}
	max = (size_t)lsearch_size;

	if ((data = calloc(max, sizeof(*data))) == NULL) {
		pr_fail_dbg("malloc");
		return EXIT_NO_RESOURCE;
	}
	if ((root = calloc(max, sizeof(*data))) == NULL) {
		free(data);
		pr_fail_dbg("malloc");
		return EXIT_NO_RESOURCE;
	}

	do {
		size_t n = 0;

		/* Step #1, populate with data */
		for (i = 0; g_keep_stressing_flag && i < max; i++) {
			void *ptr;

			data[i] = ((mwc32() & 0xfff) << 20) ^ i;
			ptr = lsearch(&data[i], root, &n, sizeof(*data), cmp);
			(void)ptr;
		}
		/* Step #2, find */
		for (i = 0; g_keep_stressing_flag && i < n; i++) {
			int32_t *result;

			result = lfind(&data[i], root, &n, sizeof(*data), cmp);
			if (g_opt_flags & OPT_FLAGS_VERIFY) {
				if (result == NULL)
					pr_fail("%s: element %zu could not be found\n", args->name, i);
				else if (*result != data[i])
					pr_fail("%s: element %zu found %" PRIu32 ", expecting %" PRIu32 "\n",
					args->name, i, *result, data[i]);
			}
		}
		inc_counter(args);
	} while (keep_stressing());

	free(root);
	free(data);
	return EXIT_SUCCESS;
}
示例#8
0
// Finds vertical lines in the given list of BLOBNBOXes. bleft and tright
// are the bounds of the image on which the input line_bblobs were found.
// The input line_bblobs list is const really.
// The output vertical_x and vertical_y are the total of all the vectors.
// The output list of TabVector makes no reference to the input BLOBNBOXes.
void LineFinder::FindLineVectors(const ICOORD& bleft, const ICOORD& tright,
                                 BLOBNBOX_LIST* line_bblobs,
                                 int* vertical_x, int* vertical_y,
                                 TabVector_LIST* vectors) {
  BLOBNBOX_IT bbox_it(line_bblobs);
  int b_count = 0;
  // Put all the blobs into the grid to find the lines, and move the blobs
  // to the output lists.
  AlignedBlob blob_grid(kLineFindGridSize, bleft, tright);
  for (bbox_it.mark_cycle_pt(); !bbox_it.cycled_list(); bbox_it.forward()) {
    BLOBNBOX* bblob = bbox_it.data();
    bblob->set_left_tab_type(TT_UNCONFIRMED);
    bblob->set_left_rule(bleft.x());
    bblob->set_right_rule(tright.x());
    bblob->set_left_crossing_rule(bleft.x());
    bblob->set_right_crossing_rule(tright.x());
    blob_grid.InsertBBox(false, true, bblob);
    ++b_count;
  }
  if (textord_debug_tabfind)
    tprintf("Inserted %d line blobs into grid\n", b_count);
  if (b_count == 0)
    return;

  // Search the entire grid, looking for vertical line vectors.
  GridSearch<BLOBNBOX, BLOBNBOX_CLIST, BLOBNBOX_C_IT> lsearch(&blob_grid);
  BLOBNBOX* bbox;
  TabVector_IT vector_it(vectors);
  *vertical_x = 0;
  *vertical_y = 1;
  lsearch.StartFullSearch();
  while ((bbox = lsearch.NextFullSearch()) != NULL) {
    if (bbox->left_tab_type() == TT_UNCONFIRMED) {
      const TBOX& box = bbox->bounding_box();
      if (AlignedBlob::WithinTestRegion(2, box.left(), box.bottom()))
        tprintf("Finding line vector starting at bbox (%d,%d)\n",
                box.left(), box.bottom());
      AlignedBlobParams align_params(*vertical_x, *vertical_y, box.width());
      TabVector* vector = blob_grid.FindVerticalAlignment(align_params, bbox,
                                                          vertical_x,
                                                          vertical_y);
      if (vector != NULL) {
        vector->Freeze();
        vector_it.add_to_end(vector);
      }
    }
  }
  ScrollView* line_win = NULL;
  if (textord_tabfind_show_vlines) {
    line_win = blob_grid.MakeWindow(0, 50, "Vlines");
    blob_grid.DisplayBoxes(line_win);
    line_win = blob_grid.DisplayTabs("Vlines", line_win);
  }
}
示例#9
0
int main()
{
    int array[] = {4, 3, 2, 5, 7, 6};
    int key = 7;
    int *found = lsearch(&key, array, 6, sizeof(int), cmpInt);
    const char *pcc[] = {"xx", "jj"};
    if(found != NULL) {
        printf("%d\n", *found);
    }
    return 0;
}
示例#10
0
int main(){int i,j,k,no,pow;
  for(i=0;i<SIZE;i++)
    ary[i]=i;
  for(i=0;i<100000;i++){
    pow=rand_r(&r_seed)%SIZE_B; 
    no = rand_r(&r_seed)%(1<<pow);
    if (!no) no=1;
    k=rand_r(&r_seed)%no;
    lsearch(&k,ary,no,sizeof(int),intcmp);
  }
  return 0;
}
示例#11
0
void testValues() {
    f = 2;
    char* result;
    char key[5], tab[10][5];
    size_t size = 9;
    
    result = lsearch(key, tab, &size, 5, strcmp);
    //@ assert result == \null || \valid(result);
    //@ assert size == 9 || size == 10;
    
    //@ assert f == 2;
    //@ assert vacuous: \false;
}
示例#12
0
void findnotes() {
    char *notes[] = {"Ab", "F#", "B", "Gb", "D"};
    char *favoriteNote = "Eb";
    char **found = lsearch(
            &favoriteNote, notes, 5, sizeof(char*), StrCmp
    );

    if (found == NULL) {
        printf("not found\n");
    } else {
        printf("found: %s", *found);
    }
}
示例#13
0
int main() {
    int array[] = {4, 2, 3, 7, 11, 6};
    int size = 6;
    int number = 7;
    void* found = lsearch(&number, array, 6, sizeof(int), intcmp);
    if (found == NULL) {
        printf("not found\n");
    } else {
        printf("found: %d\n", *((int*) found));
    }

    findnotes();
}
示例#14
0
void main()
{
 clrscr();
 float A[100];int n,ch;
 cout<<"Enter the array elements::\n";
  cin>>n;

  enter(A,n);
  display(A,n);
  isort(A,n);
  lsearch(A,n);
getch();
}
示例#15
0
int main(int argc, char *argv[]) {
    char needle[20];
    struct Entry *result;

    int action, i = 0;

    if (argc < 2) {
        fprintf(stderr, "Path to database omitted!\n");
        exit(-1);
    }

    struct List entries = parse_db(argv[1]); /* parse database */

    /* ask for criterium */
    printf("What do you want to do?:\n1) sort by name\n2) sort by residents\n3) sort by area\n4) sort by distance\n5) search for entry\nYour choice: ");
    scanf("%d", &action);

    switch(action) {
    case 1:
        quicksort(entries.start, entries.end, cmp_name);
        break;
    case 2:
        quicksort(entries.start, entries.end, cmp_residents);
        break;
    case 3:
        quicksort(entries.start, entries.end, cmp_area);
        break;
    /*case 4:
    	quicksort(entries.start, entries.end, cmp_distance);
    	break;*/
    case 5:
        printf("what are you searching: ");
        scanf("%s", needle);
        result = lsearch(needle, entries.start, entries.end);
        print_entry(result);

    default:
        fprintf(stderr, "Invalid sort criteria!\n");
    }

    /* show result */
    if (action != 5) {
        struct Node *node;
        for (node = entries.start; node != entries.end && i++ < 100; node = node->next) {
            print_entry(node->data);
        }
    }

    return 0;
}
示例#16
0
void main( int argc, const char *argv[] )
  {
    int i;
    unsigned num = 0;
    char **array = (char **)calloc( argc, sizeof(char **) );
    int compare( const void *, const void * );

    for( i = 1; i < argc; ++i ) {
      lsearch( &argv[i], array, &num, sizeof(char **),
                  compare );
    }
    for( i = 0; i < num; ++i ) {
      printf( "%s\n", array[i] );
    }
  }
示例#17
0
void *lf_hash_search(LF_HASH *hash, LF_PINS *pins, const void *key, uint keylen)
{
  LF_SLIST * volatile *el, *found;
  uint bucket, hashnr= calc_hash(hash, (uchar *)key, keylen);

  bucket= hashnr % hash->size;
  el= lf_dynarray_lvalue(&hash->array, bucket);
  if (unlikely(!el))
    return MY_ERRPTR;
  if (*el == NULL && unlikely(initialize_bucket(hash, el, bucket, pins)))
    return MY_ERRPTR;
  found= lsearch(el, hash->charset, my_reverse_bits(hashnr) | 1,
                 (uchar *)key, keylen, pins);
  return found ? found+1 : 0;
}
示例#18
0
void main()
{
 clrscr();
 float A[25],n;
 do
 {
   cout<<"Enter the no. of elements less than 25"<<endl;
     cin>>n;
 }while(n>25);
 input(A,n);
 display(A,n);
 isort(A,n);
 lsearch(A,n);
 getch();
}
示例#19
0
void main()
{
    clrscr();
    char c[10][40];
    int n;
    do
    {
        cout<<"Enter the no. of countries you want to enter (<10) : ";
        cin>>n;
    } while(n>10);
    enter(c,n);
    display(c,n);
    sort(c,n);
    lsearch(c,n);
    getch();
}
示例#20
0
void main()
	{
	clrscr();
	head();
	assign();
	clrscr();
	head();
	cout<<"\n Enter the elemet you want to search : ";
	cin>>element;
	clrscr();
	head();
	lsearch();
	clrscr();
	cout<<"\n Program implemented by Hemant Baid @ Code Library ";
	getch();
	}
示例#21
0
void dictstat_append (hashcat_ctx_t *hashcat_ctx, dictstat_t *d)
{
  hashconfig_t   *hashconfig   = hashcat_ctx->hashconfig;
  dictstat_ctx_t *dictstat_ctx = hashcat_ctx->dictstat_ctx;

  if (dictstat_ctx->enabled == false) return;

  if (hashconfig->dictstat_disable == true) return;

  if (dictstat_ctx->cnt == MAX_DICTSTAT)
  {
    event_log_error (hashcat_ctx, "There are too many entries in the %s database. You have to remove/rename it.", dictstat_ctx->filename);

    return;
  }

  lsearch (d, dictstat_ctx->base, &dictstat_ctx->cnt, sizeof (dictstat_t), sort_by_dictstat);
}
示例#22
0
main()
{
     int i,d[MAX],n,k;
     printf("Enter elements into the array: ");
     for(i=0;i<10;i++)
     {
         scanf("%d",&d[i]);
     }
     printf("Enter the number to search: ");
     scanf("%d",&n);
     k=lsearch(d,0,10,n);
     if(k==1)
           printf("Item %d found at index: %d",n,k);
     if(k=-1)
           printf("Item %d was not found.",n);
     printf("\nTotal number of comparisons done: %d",c);
     
}
示例#23
0
int main() {
    FILE *in = fopen("task.in", "r");
    FILE *out = fopen("task.out", "w");
    int array[LIMIT];
    int needle;
    int size = 1;
    
    fscanf(in, "%d", &needle);
    
    for ( int i = 0; i < LIMIT && fscanf(in, "%d", &array[i]) == 1; i++ ) {
        size += 1;
    }
    fclose(in);
    
    fprintf(out, "%d\n", lsearch(array, size, needle));
    fclose(out);
    
    return 0;
}
示例#24
0
int _tmain(int argc, _TCHAR* argv[])
{
	int a=10;
	int b=4;
/*	cout << &a << "=" << a << endl << &b << "=" << b << endl;
	Swap(&a,&b,sizeof(int));
	cout << &a << "=" << a << endl << &b << "=" << b;

	*/
	//=====================================

	char* nodes[]={"A-","E#","Bb","D"};
	char* myfavnode = "E#";
	
	char* result = (char*)lsearch(nodes,myfavnode,4,sizeof(char*),xcomp);

	cout << result << endl;	
	system("pause");
	return 0;
}
示例#25
0
void main()
{
 int array[size],i,s,ele,ans;
 char choice;
 do
  {
   clrscr();
   printf("\n\n\tEnter the size of the array : ");
   scanf("%d",&s);
   if(s>size)
    {
     printf("\n\n\t\tOverflow Error");
     printf("\n\t\tPress any key to continue");
     choice='n';
     getch();
    }
   else
    {
     printf("\n\n\tEnter the elements of the array ");
     for(i=0;i<s;i++)
      {
       printf(": ");
       scanf("%d",&array[i]);
       printf("\t\t\t\t\t");
      }
     printf("\n\n\tEnter the element to be searched : ");
     scanf("%d",&ele);
     ans=lsearch(ele,s,array);
     if(ans==0)
      printf("\n\n\n\tThe array does not consists of the element %d",ele);
     else
      printf("\n\n\n\tThe array consists of the element %d",ele);
    }
   printf("\n\n\n\n\t\tWant to continue (y/n) : ");
   scanf("%s",&choice);
  }while(choice=='y'||choice=='Y');
 getch();
}
示例#26
0
void dictstat_read (hashcat_ctx_t *hashcat_ctx)
{
  hashconfig_t   *hashconfig   = hashcat_ctx->hashconfig;
  dictstat_ctx_t *dictstat_ctx = hashcat_ctx->dictstat_ctx;

  if (dictstat_ctx->enabled == false) return;

  if (hashconfig->dictstat_disable == true) return;

  FILE *fp = fopen (dictstat_ctx->filename, "rb");

  if (fp == NULL)
  {
    // first run, file does not exist, do not error out

    return;
  }

  // parse header

  u64 v;
  u64 z;

  const size_t nread1 = hc_fread (&v, sizeof (u64), 1, fp);
  const size_t nread2 = hc_fread (&z, sizeof (u64), 1, fp);

  if ((nread1 != 1) || (nread2 != 1))
  {
    event_log_error (hashcat_ctx, "%s: Invalid header", dictstat_ctx->filename);

    fclose (fp);

    return;
  }

  v = byte_swap_64 (v);
  z = byte_swap_64 (z);

  if ((v & 0xffffffffffffff00) != (DICTSTAT_VERSION & 0xffffffffffffff00))
  {
    event_log_error (hashcat_ctx, "%s: Invalid header, ignoring content", dictstat_ctx->filename);

    fclose (fp);

    return;
  }

  if (z != 0)
  {
    event_log_error (hashcat_ctx, "%s: Invalid header, ignoring content", dictstat_ctx->filename);

    fclose (fp);

    return;
  }

  if ((v & 0xff) < (DICTSTAT_VERSION & 0xff))
  {
    event_log_warning (hashcat_ctx, "%s: Outdated header version, ignoring content", dictstat_ctx->filename);

    fclose (fp);

    return;
  }

  // parse data

  while (!feof (fp))
  {
    dictstat_t d;

    const size_t nread = hc_fread (&d, sizeof (dictstat_t), 1, fp);

    if (nread == 0) continue;

    lsearch (&d, dictstat_ctx->base, &dictstat_ctx->cnt, sizeof (dictstat_t), sort_by_dictstat);

    if (dictstat_ctx->cnt == MAX_DICTSTAT)
    {
      event_log_error (hashcat_ctx, "There are too many entries in the %s database. You have to remove/rename it.", dictstat_ctx->filename);

      break;
    }
  }

  fclose (fp);
}
int main()
{
    int test;
    
    int terminal=-999;//this is for input text, so the loop knows when to stop

    int size=100;//Initial size
    int i=0;

    int *Data=Create(size);
    
    scanf("%d",&Data[i]);//Read in our initialize variable for our array
    //printf("i:%d and val:%d\n",i,Data[i]);
    i++;
    
    //????Even without increasing the allocated space the array was not Seg faulting
    
    while (Data[i-1]!=terminal)//This looks at the previous posi
    {
        scanf("%d",&Data[i]);
        //printf("i:%d and val:%d\n",i,Data[i]);
        i++;
        if (i==size)//this counter counts up size malloced for array, if true goes into function
        {
            size=size*2;
            Data=Inc_Cap(Data,size);
        }
    }
    printf("\nReading in Data Complete\n");
    size=i-1;//the get rid of the -999 in the array because we dont want that sorted
   
    //printf("Test_shot\n");
    
    int *lsearch_numComp_P;//This is for number of comparisons because we want to return to values from functions
    int *bsearch_numComp_P;
    
    int lsearch_numComp=0;
    int bsearch_numComp=0;
    
    lsearch_numComp_P=&lsearch_numComp;//Take the address of the right because we need to point to that space
    bsearch_numComp_P=&bsearch_numComp;
    
    
    int* toArray=Create(size);//We are mallocing because to we can free it later
    
    arrayCopy(Data,toArray,size);//self- explanatory
    
    sort(Data,size);
    
    i=0;
   
    int target;//This is the value that need to be found for binary and linear search
    scanf("%d",&target);
     //printf("Target Value: %d\n",target);
    while (target!=terminal)
    {
        
        //scanf("%d",&target);
        //printf("Target Value: %d\n",target);
    
        int Print_Lsearch=lsearch(toArray,size,target,lsearch_numComp_P);//reason for this becaue we are sending the index location
    
        if (Print_Lsearch==-1)//because of the above statement is the reason for this "if" statement
        {//we dont want to run the same function twice becasue it would be unneccassay
            printf("Value not found in Linear search\n");
        }
        else
            printf("Target Value:%d found with Linear search in Array position %d with %d comparisons\n",target,Print_Lsearch,*lsearch_numComp_P);
    
    
        int Print_Bsearch=Bsearch(Data,size,target,bsearch_numComp_P);
    
        if (Print_Bsearch==-1)
        {  //Same sort of logic as lsearch explaniation for "if"
            printf("Value not found in Binary search\n");
        }
        else
            printf("Target Value:%d found with Binary search in Array position %d with %d comparisons\n",target,Print_Bsearch,*bsearch_numComp_P);
        
        lsearch_numComp=0;
        bsearch_numComp=0;
        scanf("%d",&target);
    
    }
    
    free_space(Data);
    free_space(toArray);
    
    return 0;
}
示例#28
0
文件: scan.c 项目: Ntools/n
tool(void)
{
	char buf[BUFSIZ],*p;
	unsigned short div2(char *,char **);
	struct KEY kk,*kp;
	size_t cnt;
	FILE *fp;
	int i,sts;

	keyptr = key;
	ininame = "keys.ini";
	if((fp= fopen(ininame,"r")) == NULL) {  /* Curent directory */
		if((p= getenv("KEYS")) != NULL) {
			fp= fopen(p,"r");  /* Env val directory */
		}
	}
	if(fp == NULL) {
#ifndef UNIX
		_searchenv(ininame,"PATH",buf);
#else
		sprintf(buf,"/usr/local/etc/%s", ininame);
#endif
		if((fp= fopen(buf,"r")) == NULL) return(NG);  /* PATH directory */
	}
	if((keyptr = (struct KEY *)calloc(KEYDEFMAX,sizeof(struct KEY))) == NULL)
		abort();
	cnt= 0;
	while(fgets(buf,BUFSIZ,fp) != NULL) {
		crcut(buf);
		if(buf[0] == ';' || buf[0] == '*' || buf[0] == '#') continue;
		if((kk.code = div2(buf,&p)) == 0xffff) {
			keyptr = key; break;
		}
		kk.keyword = buf;
		kp = lfind(&kk, key, &key_count,sizeof(struct KEY),cpkey);
		if(kp == NULL) {
			if(othset(&kk,buf,p) == NG) {
				ndprintf("Keyword not found [%s]!\n",buf);
				if(ynchk("Continue ?") != YES) {
#if (defined TEXT98)
					popscrn();
#elif (defined UNIX)
					ttclose();
#else
					batch("///",NULL);
#endif
					exit(1);
				}
			}
			continue;
		}
		kk.func = kp->func;
		kk.helpmsg = kp->helpmsg;
		if(key_count < KEYDEFMAX) {
			if(cnt) kp = lfind(&kk, keyptr, &cnt,sizeof(struct KEY), codekey);
			else kp= NULL;
			if(kp == NULL) {
				kk.keyword= memgets(buf);
				lsearch(&kk, keyptr, &cnt, sizeof(struct KEY), codekey);
			}
		}
	}
	key_count= cnt;
	fclose(fp);
}
示例#29
0
文件: gcrregp.c 项目: oeli/yafra
void xGRcreate_regionpoint(REGIONPOINT *regpkt)
{
	extern unsigned long anzregionPoints;
	extern REGIONPOINT	*regionPoints;

	static unsigned long resregionPoints = 0;

	int xGRcomp_regionpoint_kor(void *, void *);
	int xGRcomp_regionpoint_num(void *, void *);
	int			(*func)(const void *, const void *);
	REGIONPOINT *found;
	long			i, j; 
	Boolean		exist;

	/*--- Alloc for array ---------------------------------------*/
	regionPoints = (REGIONPOINT *)xUIalloc((void *)regionPoints,
								(long *)&resregionPoints, ANZMEMPKT, anzregionPoints+1,
								 sizeof(REGIONPOINT));

#ifdef PS_SEARCH
	/*--- create at end when not existent -----------------------*/
	found = (REGIONPOINT *)lsearch((const void *)regpkt,
										(void *)regionPoints, (size_t)&anzregionPoints,
										sizeof(REGIONPOINT), xGRcomp_regionpoint_kor);
	/*--- search  then add -------------------------------------*/
	func = xGRcomp_regionpoint_num_b;
	found = (REGIONPOINT *)bsearch((const void *)regpkt,
					(void *)regionPoints, (size_t)anzregionPoints,
					sizeof(REGIONPOINT), func);
	if (found->n == 0) {
		found->n = anzregionPoints;
	}

#endif

	/*--- look for matching x,y -------*/
	exist = False;
	for ( j=anzregionPoints, i=0;  (i < anzregionPoints) ;  i++)  {
		found = &regionPoints[i];
		if ((regpkt->p.x == found->p.x) && (regpkt->p.y == found->p.y)) {
			j=i;
			break;
		} 
	}  

#ifdef DEBUG_REGION
	fprintf(rpfile, "i:%ld  ",  i );
#endif

	/*--- check if not found ----------*/
	if (j >= anzregionPoints) {
		found = 0;
		anzregionPoints++;
		found = (REGIONPOINT *)XtMalloc(sizeof(REGIONPOINT));
		found->n = anzregionPoints;
		found->p.x = regpkt->p.x ;
		found->p.y = regpkt->p.y ;
/*!!!		regionPoints[(anzregionPoints)-1] = *found;  */
		memcpy((void *)&regionPoints[anzregionPoints-1], (void *)found, sizeof(REGIONPOINT));

#ifdef DEBUG_REGION
		fprintf(rpfile, "rp:%ld \n",  anzregionPoints );
#endif
	} 
	
	regpkt->n = found->n;
	return;
}
示例#30
0
int main(int argc, char **argv)
{
  unsigned long long i,j,k;
  unsigned int red_var,green_var,blue_var,alpha_var,timestep;
  color_t colors[257]; /* one extra for error handling */
  size_t num_colors = 0;

  atexit(cleanup);

  if(argc != 2 && argc != 8)
    {
      printf("Every color in the input RawVRGBA file (RawV with 4 variables: red, green, blue, and alpha)\n"
	     "will be mapped to some voxel value range within [0-255] in the output rawiv file (unsigned char volume).\n"
	     "The number of values in each color's range is dependent on the number of different voxel colors in the\n"
	     "RawVRGBA volume. The input voxel's alpha value will determine which value within each color's selected\n"
	     "range the output voxel will take.  If the input voxel's alpha value is 0, then the value in the output volume\n"
	     "will be 0. Due to the fact that the output volume voxels are of unsigned char\n"
	     "type, the maximum number of different colors that can be represented in the output volume are 256.  If\n"
	     "there are more than 256 colors, those colors will cause their corresponding output voxel to take the value\n"
	     "0.\n\n");
      printf("Usage: %s <input rawv with >=4 variables> <red var> <green var> <blue var> <alpha var> <timestep> <output rawiv>\n\n",argv[0]);
      printf("Example: %s heart.rawv 0 1 2 3 0 heart.rawiv\n"
	     "Most RawVRGBA files have the RGBA variables in order, thus the above example should work in most cases.\n"
	     "To produce a rendering similar to the RGBA rendering of the input RawV file, make sure to map each voxel\n"
	     "value range to the color used in the RawV file.",argv[0]);
      return 0;
    }

  vol = new MappedRawVFile(argv[1],true,true);
  if(!vol->isValid())
    {
      printf("Error loading %s!\n",argv[1]);
      return 1;
    }

  printf("File: %s\n",argv[1]);
  printf("Num Vars: %d\n",vol->numVariables());
  printf("Vars: ");
  for(i=0; i<vol->numVariables(); i++) printf("%s ",vol->get(i,0)->name());
  printf("\n");
  printf("Num Timesteps: %d\n",vol->numTimesteps());
  printf("Dimensions: %d x %d x %d\n",vol->XDim(),vol->YDim(),vol->ZDim());
  printf("Span: %lf x %lf x %lf\n",vol->XSpan(),vol->YSpan(),vol->ZSpan());
  printf("TSpan: %lf\n",vol->TSpan());

  if(argc == 2) { return 0; } /* only need to print out volume info */

  red_var = atoi(argv[2]);
  green_var = atoi(argv[3]);
  blue_var = atoi(argv[4]);
  alpha_var = atoi(argv[5]);
  timestep = atoi(argv[6]);

  outvol = fopen(argv[7],"wb+");
  if(outvol == NULL)
    {
      char err_str[512];
      sprintf(err_str,"Error opening %s",argv[7]);
      perror(err_str);
      return 1;
    }

  unsigned long long len = vol->XDim()*vol->YDim()*vol->ZDim()*sizeof(unsigned char)+68;

  /* create the header for the new file */
  RawIVHeader header;
  header.min[0] = 0.0; header.min[1] = 0.0; header.min[2] = 0.0;
  header.max[0] = (vol->XDim()-1)*vol->XSpan();
  header.max[1] = (vol->YDim()-1)*vol->YSpan();
  header.max[2] = (vol->ZDim()-1)*vol->ZSpan();
  header.numVerts = vol->XDim()*vol->YDim()*vol->ZDim();
  header.numCells = (vol->XDim()-1)*(vol->YDim()-1)*(vol->ZDim()-1);
  header.dim[0] = vol->XDim(); header.dim[1] = vol->YDim(); header.dim[2] = vol->ZDim();
  header.origin[0] = 0.0; header.origin[1] = 0.0; header.origin[2] = 0.0;
  header.span[0] = vol->XSpan(); header.span[1] = vol->YSpan(); header.span[2] = vol->ZSpan();
	
  if(!big_endian())
    {
      for(i=0; i<3; i++) SWAP_32(&(header.min[i]));
      for(i=0; i<3; i++) SWAP_32(&(header.max[i]));
      SWAP_32(&(header.numVerts));
      SWAP_32(&(header.numCells));
      for(i=0; i<3; i++) SWAP_32(&(header.dim[i]));
      for(i=0; i<3; i++) SWAP_32(&(header.origin[i]));
      for(i=0; i<3; i++) SWAP_32(&(header.span[i]));
    }

  fwrite(&header,sizeof(RawIVHeader),1,outvol);
	
  /* get a slice at a time because it's quicker */
  unsigned char *slice[5]; /* [0-3] == rgba slices, [4] == output slice */
  for(i=0; i<5; i++) slice[i] = (unsigned char *)malloc(vol->XDim()*vol->YDim()*sizeof(unsigned char));
	
  for(k=0; k<vol->ZDim(); k++)
    {
      /* get the colors for this slice (ignoring alpha for now) */
      vol->get(red_var,timestep)->getMapped(0,0,k,vol->XDim(),vol->YDim(),1,slice[0]);
      vol->get(green_var,timestep)->getMapped(0,0,k,vol->XDim(),vol->YDim(),1,slice[1]);
      vol->get(blue_var,timestep)->getMapped(0,0,k,vol->XDim(),vol->YDim(),1,slice[2]);
	  
      /* check each colored voxel and add all new colors to the list to determine output voxel ranges */
      color_t color;
      for(i=0; i<vol->XDim(); i++)
	for(j=0; j<vol->YDim(); j++)
	  {
	    if(num_colors > 256)
	      {
		printf("Warning: more than 256 colors! Any color not in the list will result in a zero output voxel.\n");
		num_colors = 256;
		goto docalc;
	      }
		
	    color.r = slice[0][i+j*vol->XDim()];
	    color.g = slice[1][i+j*vol->XDim()];
	    color.b = slice[2][i+j*vol->XDim()];
		  
	    if(lsearch(&color,colors,&num_colors,sizeof(color_t),color_cmp) == NULL)
	      {
		printf("Error in lsearch()!\n");
		return 1;
	      }
	  }
		
      fprintf(stderr,"Determining color list... %5.2f %%   \r",(((float)k)/((float)((int)(vol->ZDim()-1))))*100.0);
    }
  printf("\n");
	
 docalc:;

  printf("Number of colors: %d\n",num_colors);
  printf("Colors: ");
  for(i=0; i<num_colors; i++)
    printf("(%d,%d,%d) ",colors[i].r,colors[i].g,colors[i].b);
  printf("\n");
  unsigned int range_size = 256/num_colors; /* range size == the whole space divided by the number of found colors */
  printf("Range size: %d\n",range_size);
	
  /* now write the output volume */
  for(k=0; k<vol->ZDim(); k++)
    {
      /* get the colors for this slice */
      vol->get(red_var,timestep)->getMapped(0,0,k,vol->XDim(),vol->YDim(),1,slice[0]);
      vol->get(green_var,timestep)->getMapped(0,0,k,vol->XDim(),vol->YDim(),1,slice[1]);
      vol->get(blue_var,timestep)->getMapped(0,0,k,vol->XDim(),vol->YDim(),1,slice[2]);
      vol->get(alpha_var,timestep)->getMapped(0,0,k,vol->XDim(),vol->YDim(),1,slice[3]);
	  
      /* lookup each color to determine it's output voxel value */
      /* check each colored voxel and add all new colors to the list to determine output voxel ranges */
      color_t color,*cur;
      unsigned int index, min, max;
      for(i=0; i<vol->XDim(); i++)
	for(j=0; j<vol->YDim(); j++)
	  {
	    color.r = slice[0][i+j*vol->XDim()];
	    color.g = slice[1][i+j*vol->XDim()];
	    color.b = slice[2][i+j*vol->XDim()];
		  
	    cur = (color_t *)lfind(&color,colors,&num_colors,sizeof(color_t),color_cmp);
	    if(cur == NULL)
	      {
		slice[4][i+j*vol->XDim()] = 0;
		continue;
	      }
	    index = ((unsigned int)(cur - colors)); /* determine the color's index */
	    min = index*range_size; /* find the start of this color's range */
	    max = min+range_size-1; /* find the end of this color's range */ /* Note: due to the discreet nature of unsigned char,
										we may not use the entire available 256 voxel values.
									     */
	    /* now use the color's alpha value to determine where on the range the output voxel is */
	    slice[4][i+j*vol->XDim()] = slice[3][i+j*vol->XDim()] == 0 ? 0 : (unsigned char)(min + float(range_size-1)*(float(slice[3][i+j*vol->XDim()])/255.0));
	  }
	
      fwrite(slice[4],sizeof(unsigned char),vol->XDim()*vol->YDim(),outvol);
	
      fprintf(stderr,"Writing output volume... %5.2f %%   \r",(((float)k)/((float)((int)(vol->ZDim()-1))))*100.0);
    }
  printf("\n");
	
  for(i=0; i<5; i++) free(slice[i]);
	
  return 0;
}