Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the C library function to generate random string?

Tags:

c

Is there a library function that creates a random string in the same way that mkstemp() creates a unique file name? What is it?

like image 940
cody Avatar asked Apr 02 '13 15:04

cody


2 Answers

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] = '\1' }; // make the last character non-zero so we can test based on it later
    rand_str(str, sizeof str - 1);
    assert(str[41] == '\0');      // 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 = '\0';
}

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.

like image 52
autistic Avatar answered Oct 26 '22 18:10

autistic


There's no build in API, you may use (on *x system) /dev/urandom like:

FILE *f = fopen( "/dev/urandom", "r");
if( !f) ...
fread( binary_string, string_length, f);
fclose(f);

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():

#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 '}'
}

And if you need really random string you need to google generating random sequence cryptography which is one of cryptography's difficult problems which still hasn't perfect solution :)

like image 23
Vyktor Avatar answered Oct 26 '22 18:10

Vyktor