Skip to content

Instantly share code, notes, and snippets.

@Keith-S-Thompson
Created February 4, 2013 02:38
Show Gist options
  • Save Keith-S-Thompson/4704720 to your computer and use it in GitHub Desktop.
Save Keith-S-Thompson/4704720 to your computer and use it in GitHub Desktop.
Generate random numbers from /dev/urandom
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 36
#define URANDOM_DEVICE "/dev/urandom"
static FILE *urandom;
/*
* Returns a random number from 0 to MAX-1
*/
int random_number(void) {
int c;
do {
c = fgetc(urandom);
if (c == EOF) {
fprintf(stderr, "Failed to read from %s\n", URANDOM_DEVICE);
exit(EXIT_FAILURE);
}
}
while (c >= (UCHAR_MAX + 1) / MAX * MAX);
return c % MAX;
}
int main(void) {
urandom = fopen(URANDOM_DEVICE, "rb");
if (urandom == NULL) {
fprintf(stderr, "Failed to open %s\n", URANDOM_DEVICE);
exit(EXIT_FAILURE);
}
for (int i = 0; i < 10; i ++) {
printf("%d\n", random_number());
}
fclose(urandom);
return 0;
}
@Keith-S-Thompson
Copy link
Author

Keith-S-Thompson commented Feb 4, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment