Skip to content
Snippets Groups Projects
hashtable-test.c 1.07 KiB
Newer Older
Bruce Cowan's avatar
Bruce Cowan committed
/*
 * SPDX-FileCopyrightText: 2018-2023 Bruce Cowan <bruce@bcowan.me.uk>
Bruce Cowan's avatar
Bruce Cowan committed
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
Bruce Cowan's avatar
Bruce Cowan committed
 */

Bruce Cowan's avatar
Bruce Cowan committed
#include <stdio.h>
Bruce Cowan's avatar
Bruce Cowan committed
#include <stdlib.h>
#include <string.h>

Bruce Cowan's avatar
Bruce Cowan committed
#include <hashtable.h>
Bruce Cowan's avatar
Bruce Cowan committed

static void
add_data (HashTable *table)
{
Bruce Cowan's avatar
Bruce Cowan committed
  char key[20];
  char value[20];

  printf ("Input the key ");
  scanf ("%s", key);
  printf ("Input the value ");
  scanf ("%s", value);

  hash_table_insert (table, strdup (key), strdup (value));

  char *key_lookup = strndup (key, strlen (key));
  printf ("The last one inserted was: {'%s': ", key_lookup);
  const char *val = hash_table_lookup (table, key);
  printf ("'%s'}\n", val);

  free (key_lookup);
}

static void
Bruce Cowan's avatar
Bruce Cowan committed
print_all (                 void *key,
                            void *value,
           [[maybe_unused]] void *)
Bruce Cowan's avatar
Bruce Cowan committed
{
  printf ("%s:%s\n", (const char *) key, (const char *) value);
}
Bruce Cowan's avatar
Bruce Cowan committed

int
main (void)
{
Bruce Cowan's avatar
Bruce Cowan committed
  HashTable *table;
Bruce Cowan's avatar
Bruce Cowan committed
  table = hash_table_new (str_hash, str_equal, free, free);
Bruce Cowan's avatar
Bruce Cowan committed
  while (1)
  {
    add_data (table);
    hash_table_foreach (table, print_all, nullptr);
Bruce Cowan's avatar
Bruce Cowan committed
  }
Bruce Cowan's avatar
Bruce Cowan committed
  return 0;