什么是C库函数生成随机字符串? [英] What's the C library function to generate random string?
问题描述
有没有以同样的方式, mkstemp()
创建一个唯一的文件名创建一个随机字符串的库函数?这是什么?
Is there a library function that creates a random string in the same way that mkstemp()
creates a unique file name? What is it?
推荐答案
有没有标准的功能,但你的操作系统可能实现的东西。你有没有考虑通过手册搜索?另外,这个任务是很简单的。我会尝试使用类似:
There's no standard function, but your OS might implement something. Have you considered searching through the manuals? Alternatively, this task is simple enough. I'd be tempted to use something like:
void rand_str(char *dest, size_t length) {
char charset[] = "0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
while (length-- > 0) {
size_t index = (double) rand() / RAND_MAX * (sizeof charset - 1);
*dest++ = charset[index];
}
*dest = '\0';
}
这对EBCDIC系统的正常工作,并能适应几乎任何字符集的整齐的利益。我还没有添加任何下列字符到字符集,因为它似乎很清楚,你想要的字符串,可以是文件名:
This has the neat benefit of working correctly on EBCDIC systems, and being able to accommodate virtually any character set. I haven't added any of the following characters into the character set, because it seems clear that you want strings that could be filenames:
":;?@[\]^_`{|}"
我想通很多这些人物能够在各种操作系统的文件名是无效的。
I figured many of those characters could be invalid in filenames on various OSes.
这篇关于什么是C库函数生成随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!