简体   繁体   English

在 C++ 中生成随机文件名

[英]Generate a random filename in C++

I am working on an object-detection application in C++.我正在使用 C++ 开发一个对象检测应用程序。 And I store each false negative images, so I need a random file name generator, which should not duplicate them.我存储每个假阴性图像,所以我需要一个随机文件名生成器,它不应该复制它们。

I am currently using tmpnam , but it does not guarantee uniqueness, so files could be overwritten, because all files are stored in same folder.我目前正在使用tmpnam ,但它不保证唯一性,因此文件可能会被覆盖,因为所有文件都存储在同一文件夹中。

I am looking for any other way to generate unique file names.我正在寻找任何其他方式来生成唯一的文件名。

I would suggest using GUID's.我建议使用 GUID。 As stated they are not 100% guaranteed but for your purposes they are probably going to be just fine.如前所述,它们不是 100% 保证的,但出于您的目的,它们可能会很好。

I've attached the code:我附上了代码:

#include <Windows.h>
#include <iostream>
#include <objbase.h>

int main()
{
    GUID guid;
    CoCreateGuid(&guid);

    printf("%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX",
        guid.Data1, guid.Data2, guid.Data3,
        guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
        guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
    system("pause");
    return 0;
}

This is going to return the unique name as 32 hex digits grouped into chunks of 8-4-4-4-12 .这将返回唯一名称作为32 个十六进制数字分组到 8-4-4-4-12 块中

Upon running the code on my machine it provided a GUID of: CAF9B27A-AA9E-46DE-9966-C3EDBE5D674F在我的机器上运行代码后,它提供了一个 GUID: CAF9B27A-AA9E-46DE-9966-C3EDBE5D674F

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM