linux uuid c,linux c 生成uuid

/********方法一**********/

#include

#include

#include

/**

* Create random UUID

*

* @param buf - buffer to be filled with the uuid string

*/

char *random_uuid( char buf[37] )

{

const char *c = "89ab";

char *p = buf;

int n;

for( n = 0; n < 16; ++n )

{

int b = rand()%255;

switch( n )

{

case 6:

sprintf(p, "4%x", b%15 );

break;

case 8:

sprintf(p, "%c%x", c[rand()%strlen(c)], b%15 );

break;

default:

sprintf(p, "%02x", b);

break;

}

p += 2;

switch( n )

{

case 3:

case 5:

case 7:

case 9:

*p++ = '-';

break;

}

}

*p = 0;

return buf;

}

void main()

{

char guid[37];

random_uuid(guid);

printf("guid = %s

", guid);

random_uuid(guid);

printf("guid = %s

", guid);

random_uuid(guid);

printf("guid = %s

", guid);

random_uuid(guid);

printf("guid = %s

", guid);

}

运行如下:

daniel@debian:~/src$ gcc getuuid.c

daniel@debian:~/src$ ./a.out

guid = a397a255-53be-41fc-996b-521413e9e22d

guid = 518e1f56-0857-49a7-a5d0-528277751b99

guid = 4aed583d-6a52-49d5-b668-8ead955f3c35

guid = b5c48cdd-6c11-453d-91b4-59cfce233d27

daniel@debian:~/src$

/********方法二**********/

/*libuuid是一个用于生成UUID的C库,具体用法参考http://linux.die.net/man/3/libuuid,示例如下:*/

#include

#include

int main(int argc, char **argv)

{

uuid_t uuid;

char str[36];

uuid_generate(uuid);

uuid_unparse(uuid, str);

printf("%s

", str);

return 0;

}

在Linux下编译时需要链接uuid库

gcc -o uuid uuid.c -luuid

在Ubuntu中,可以用下面的命令安装libuuid:

sudo apt-get install uuid-dev

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值