浅析uthash系列之三:打印uthash工具

打印uthash

uthash版本 :2.0.2
作者:jafon.tian
转载请注明出处:https://blog.youkuaiyun.com/JT_Notes

为了能直观的看到hash表的情况,下面提供一种将hash表详情打印到标准输出或文件的方式。

  • 整套打印采用宏定义的方式,对外提供两个API函数
名称 参数
PRINT_UTHASH (head)
基于PRINT_UTHASH_HH的宏
PRINT_UTHASH_HH (hh, head)
hh为句柄成员名称
head为hash表指针
  • hash表内容打印到标准输出或文件

在包含printHashTable.h之前定义PRINT_FILE_ENABLE使能输出到文件,通过PRINT_FILE_FULLPATH定义文件全路径,缺省输出到”/tmp/print_uthash_table.txt”。

  • 使用tests/test2.c举例演示使用方式
#include "uthash.h"
#include <time.h>
#include <stdlib.h>   /* malloc */
#include <stdio.h>    /* printf */

//使能打印到文件 !!!
#define PRINT_FILE_ENABLE
//指定打印文件全路径,默认路径是"/tmp/print_uthash_table.txt" !!!
#define PRINT_FILE_FULLPATH "./print_uthash_table.txt"
#include "printHashTable.h"
//添加头文件 !!!
#include "printHashTable.h"

typedef struct example_user_t {
    int id;
    int cookie;
    UT_hash_handle hh;
} example_user_t;

int main(int argc,char *argv[])
{
    int i;
    example_user_t *user, *tmp, *users=NULL;

    // 打印hash表 !!!
    PRINT_UTHASH(users); 

    /* create elements */
    for(i=0; i<10; i++) {
        user = (example_user_t*)malloc(sizeof(example_user_t));
        if (user == NULL) {
            exit(-1);
        }
        user->id = i;
        user->cookie = i*i;
        HASH_ADD_INT(users,id,user);
    }

    // 打印hash表 !!!
    PRINT_UTHASH(users);

    /* find each even ID */
    for(i=0; i<10; i+=2) {
        HASH_FIND_INT(users,&i,tmp);
        if (tmp != NULL) {
            printf("user id %d found, cookie %d\n", tmp->id, tmp->cookie);
        } else {
            printf("user id %d not found\n", i);
        }
    }
    return 0;
}

输出如下内容

invalid arg head 
PRINT_UTHASH fail, ret = -100
============================================== TABLE INFORMATION ==============================================
Address    ideal num_buckets log2_num_buckets num_items  hho ideal_cmax nonideal_items ineff_ex noex overhead  
---------- ----- ----------- ---------------- --------- ---- ---------- -------------- -------- ---- ----------
0x1338060   100%          32                5        10    8          0              0       ok   ok 1136      

************** BUCKET(     1) INFORMATION : Address:0x13380c0          count:1               expand_mult:0          
hashv:74401341    | key:9         | keylen:   4

************** BUCKET(     4) INFORMATION : Address:0x13380f0          count:1               expand_mult:0          
hashv:B68EF0E4    | key:3         | keylen:   4

************** BUCKET(     5) INFORMATION : Address:0x1338100          count:3               expand_mult:0          
hashv:0DB3B8E5    | key:4         | keylen:   4 <===>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值