Skip to content

Instantly share code, notes, and snippets.

@owenjones
Last active July 8, 2020 18:12
Show Gist options
  • Save owenjones/74f8d9712ad498d00d3f to your computer and use it in GitHub Desktop.
Save owenjones/74f8d9712ad498d00d3f to your computer and use it in GitHub Desktop.
Simple random string generator
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
void usage(char *file, int status) {
printf("Generates a string of random characters "
"(using numbers and upper/lowercase letters, unless otherwise specified).\n");
printf("usage: %s length [options]\n\n", file);
printf("Options:\n");
printf(" -n\tuse numbers\n");
printf(" -a\tuse lowercase letters\n");
printf(" -A\tuse uppercase letters\n");
printf(" -s\tuse symbols\n");
printf(" -c\tdisplay the character set in use\n");
exit(status);
}
int main(int argc, char* argv[]) {
srand(time(NULL) * (int) getpid());
char *file = argv[0];
if(argc < 2) usage(file, EXIT_SUCCESS);
int length = atoi(argv[1]);
if(length <= 0) {
printf("%s: invalid length -- %s\n\n", file, argv[1]);
usage(file, EXIT_FAILURE);
}
//Correct args so getopt() doesn't get confused
argv[1] = file;
argv++;
argc--;
int opt;
int useNumbers = 0;
int useLowercase = 0;
int useUppercase = 0;
int useSymbols = 0;
int showCharset = 0;
while((opt = getopt(argc, argv, "naAsc")) != -1) {
switch(opt) {
case 'n' : useNumbers = 1; break;
case 'a' : useLowercase = 1; break;
case 'A' : useUppercase = 1; break;
case 's' : useSymbols = 1; break;
case 'c' : showCharset = 1; break;
default : printf("\n"); usage(file, EXIT_FAILURE);
}
}
const char *num = "0123456789";
const char *lower = "abcdefghijklmnopqrstuvwxyz";
const char *upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
char *charset = malloc(95 * sizeof(char));
if(!useNumbers && !useLowercase && !useUppercase && !useSymbols) useNumbers = useLowercase = useUppercase = 1;
if(useNumbers) strncat(charset, num, strlen(num));
if(useLowercase) strncat(charset, lower, strlen(lower));
if(useUppercase) strncat(charset, upper, strlen(upper));
if(useSymbols) strncat(charset, symbols, strlen(symbols));
if(showCharset) printf("Using character set: %s\n", charset);
size_t i;
for(i = 0; i < length; i++) {
size_t index = (double) rand() / RAND_MAX * strlen(charset);
printf("%c", charset[index]);
}
printf("\n");
free(charset);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment