gpt4 book ai didi

c - 在 C 中生成随机 UUID

转载 作者:太空狗 更新时间:2023-10-29 15:31:20 27 4
gpt4 key购买 nike

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

我希望有一种简单的方法可以在内部执行此操作,但如果没有,system("uuidgen -r") 也可以。

最佳答案

此功能由 libuuid 提供. (Debian 上的软件包 libuuid1uuid-dev。)

这是一个生成基于熵的(随机)UUID 并将其写入 stdout 的简单程序, 然后以状态 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 uuid[37];)。确保使用 -luuid 进行编译这样链接器就知道 uuid_generate_random()uuid_unparse()libuuid 中定义.

关于c - 在 C 中生成随机 UUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51053568/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com