summaryrefslogtreecommitdiffstats
path: root/lib/randstring.c
blob: dd5ca8fceb52c9c376d29468e702bd15baa181f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma once
#include <time.h>
char *randstring(size_t length) {

    static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";        
    char *randomString = NULL;
		time_t t;
    if (length) {
        randomString = malloc(sizeof(char) * (length +1));
				srand((unsigned) time(&t));
        if (randomString) {            
            for (int n = 0;n < length;n++) {            
                int key = rand() % (int)(sizeof(charset) -1);
                randomString[n] = charset[key];
            }

            randomString[length] = '\0';
        }
    }

    return randomString;
}