zoukankan      html  css  js  c++  java
  • linux c 生成uuid

    /********方法一**********/<br>#include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    /**
     * 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);
    }

      运行如下:

    1
    2
    3
    4
    5
    6
    7
    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$

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    /********方法二**********/
    /*libuuid是一个用于生成UUID的C库,具体用法参考http://linux.die.net/man/3/libuuid,示例如下:*/
     
    #include <stdio.h>
    #include <uuid/uuid.h>
     
    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
  • 相关阅读:
    给python脚本传递命令行参数
    python.exe和pythonw.exe的区别(区分.py、.pyw、.pyc文件)
    python包管理器pip
    python从新手到安装指南
    python基础知识
    使用Lua做为MMOARPG游戏逻辑开发脚本的一点体会
    游戏中各音效的音量默认值
    Unity Editor自定义菜单排序(MenuItem Order)
    没有安装vs通过Rider编译Dll
    MyBatis-Plus 代码生成器
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318201.html
Copyright © 2011-2022 走看看