在C中生成随机UUID

比利

我将如何在C语言中生成基于熵的UUID并将其存储为字符串(字符指针)?

我希望有一个简单的方法可以在内部进行此操作,但是system("uuidgen -r")如果没有的话它将可以工作。

比利

此功能由提供libuuid(打包libuuid1uuid-dev在Debian上。)

这是一个简单的程序,它生成基于熵的(随机)UUID并将其写入stdout,然后以status退出0

/* For malloc() */
#include <stdlib.h>
/* For puts()/printf() */
#include <stdio.h>
/* For uuid_generate() and uuid_unparse() */
#include <uuid/uuid.h>


/* Uncomment to always generate capital UUIDs. */
//#define capitaluuid true

/* Uncomment to always generate lower-case UUIDs. */
//#define lowercaseuuid true

/*
 * Don't uncomment either if you don't care (the case of the letters
 * in the 'unparsed' UUID will depend on your system's locale).
 */


int main(void) {
    uuid_t binuuid;
    /*
     * Generate a UUID. We're not done yet, though,
     * for the UUID generated is in binary format 
     * (hence the variable name). We must 'unparse' 
     * binuuid to get a usable 36-character string.
     */
    uuid_generate_random(binuuid);

    /*
     * uuid_unparse() doesn't allocate memory for itself, so do that with
     * malloc(). 37 is the length of a UUID (36 characters), plus '\0'.
     */
    char *uuid = malloc(37);

#ifdef capitaluuid
    /* Produces a UUID string at uuid consisting of capital letters. */
    uuid_unparse_upper(binuuid, uuid);
#elif lowercaseuuid
    /* Produces a UUID string at uuid consisting of lower-case letters. */
    uuid_unparse_lower(binuuid, uuid);
#else
    /*
     * Produces a UUID string at uuid consisting of letters
     * whose case depends on the system's locale.
     */
    uuid_unparse(binuuid, uuid);
#endif

    // Equivalent of printf("%s\n", uuid); - just my personal preference
    puts(uuid);

    return 0;
}

uuid_unparse()不分配它自己的内存;为了避免执行时出现分段错误,您必须使用手动完成操作uuid = malloc(37);(您也可以将UUID存储在该长度的char数组中char uuid[37];)。确保进行编译,以-luuid使链接器知道uuid_generate_random()uuid_unparse()在中定义libuuid

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章