C语言 生成随机字符串的 C 库函数是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15767691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the C library function to generate random string?
提问by cody
Is there a library function that creates a random string in the same way that mkstemp()creates a unique file name? What is it?
是否有库函数以创建mkstemp()唯一文件名的相同方式创建随机字符串?它是什么?
回答by autistic
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:
没有标准功能,但您的操作系统可能会实现某些功能。您是否考虑过在手册中进行搜索?或者,这个任务很简单。我很想使用类似的东西:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void rand_str(char *, size_t);
int main(void) {
char str[] = { [41] = '' }; // make the last character non-zero so we can test based on it later
rand_str(str, sizeof str - 1);
assert(str[41] == '":;?@[\]^_`{|}"'); // test the correct insertion of string terminator
puts(str);
}
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 = 'FILE *f = fopen( "/dev/urandom", "r");
if( !f) ...
fread( binary_string, string_length, f);
fclose(f);
';
}
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:
这具有在 EBCDIC 系统上正确工作的好处,并且能够适应几乎任何字符集。我没有在字符集中添加以下任何字符,因为很明显您想要可以是文件名的字符串:
#include <time.h>
#include <stdlib.h>
// In main:
srand(time(NULL));
for( int i = 0; i < string_length; ++i){
string[i] = '0' + rand()%72; // starting on '0', ending on '}'
}
I figured many of those characters could be invalid in filenames on various OSes.
我认为其中许多字符在各种操作系统的文件名中可能无效。
回答by Vyktor
There's no build in API, you may use (on *x system) /dev/urandomlike:
没有内置 API,您可以使用(在 *x 系统上),/dev/urandom例如:
Note that this will create binary data, not string data so you'll may have to filter it afterwards.
请注意,这将创建二进制数据,而不是字符串数据,因此您可能必须在之后对其进行过滤。
You may also use standard pseudorandom generator rand():
您也可以使用标准伪随机生成器rand():
And if you need really random string you need to google generating random sequence cryptographywhich is one of cryptography's difficult problems which still hasn't perfect solution :)
如果你需要真正的随机字符串,你需要谷歌generating random sequence cryptography这是密码学的难题之一,仍然没有完美的解决方案:)

