File Archive

 
Output of file : EXAMPLE.C contained in archive : AVLBST11.ZIP

/* implementation of a simple "environment". identifiers are
associated with arbitrary strings */

#include
#include

#include "sortlist.h"

typedef struct
{
char *id;
char *value;
}
ID_WITH_VALUE;

int key_elem_compare(const void *id, const void *id_with_value)
{
return(stricmp((char *) id, ((ID_WITH_VALUE *) id_with_value)->id));
}

int elem_elem_compare(const void *id_with_value_1,
const void *id_with_value_2)
{
return(stricmp(((ID_WITH_VALUE *) id_with_value_1)->id,
((ID_WITH_VALUE *) id_with_value_2)->id));
}

typedef SORT_LIST ENV;

/* initialize environment to empty state */
void init_env
(
ENV *e
)
{
init_sort_list(e, sizeof(ID_WITH_VALUE),
elem_elem_compare, key_elem_compare);

return;
}

/* add id - value pair to environment */
int add_env(ENV *e, char *id, char *value)
{
ID_WITH_VALUE iv;

iv.id = malloc(strlen(id) + 1);
if (!iv.id)
return(-1);
iv.value = malloc(strlen(value) + 1);
if (!iv.value)
return(-1);
strcpy(iv.id, id);
strcpy(iv.value, value);

if (add_sort_list(e, (void *) &iv) != SL_SUCCESS)
return(-1);
return(0);
}

/* find value that goes with id */
char *find_env(ENV *e, char *id)
{
ID_WITH_VALUE *iv =
(ID_WITH_VALUE *) find_sort_list(e, MATCH_EQUAL, id);

if (!iv)
return((char *) 0);

return(iv->value);
}

/* remove id - value pair from environment */
void del_env(ENV *e, char *id)
{
ID_WITH_VALUE iv;

if (delete_sort_list(e, id, (void *) &iv) == SL_SUCCESS)
{
free(iv.id);
free(iv.value);
}

return;
}

static int prn_apply(void *id_with_value, void *dummy)
{
printf("%s=%s\n", ((ID_WITH_VALUE *) id_with_value)->id,
((ID_WITH_VALUE *) id_with_value)->value);

return(0);
}

/* print environment in ascending order */
void print_env(ENV *e)
{
apply_sort_list(e, prn_apply, (void *) 0, 1, (void *) 0);

return;
}

static int clear_apply(void *id_with_value, void *dummy)
{
free(((ID_WITH_VALUE *) id_with_value)->id);
free(((ID_WITH_VALUE *) id_with_value)->value);

return(0);
}

/* delete everything in environment */
void clear_env(ENV *e)
{
apply_sort_list(e, clear_apply, (void *) 0, 1, (void *) 0);

clear_sort_list(e);

return;
}