Files
random-chars/main.c
2019-10-13 18:59:52 -03:00

51 lines
1.5 KiB
C

#include "stdio.h"
#include "stdlib.h"
#include "limits.h"
#include "sodium.h"
#include "strtoui.h"
/**
* Maps a number that is between i_min and i_max to the range o_min and o_max
*/
int map(int i, int i_min, int i_max, int o_min, int o_max) {
double r = (double)(o_max - o_min) / (double)(i_max - i_min);
int j = (double) (i - i_min) * r + o_min;
return j;
}
int main(int argc, char *argv[]) {
//if doesnt have any argument just show a usage info
if(argc == 1) {
puts("Usage:\tchars [length]");
puts("\t0 > lenght > UINT_MAX");
puts("Description:");
puts("\t Generates a random string with the specified length");
exit(EXIT_SUCCESS);
}
//read the length argument and parse it to a an unsigned int
unsigned int len;
enum strtoui_error error = strtoui(&len, argv[1], 10);
if(error == STRTOUI_OVERFLOW){
fputs("The input is too big\n", stderr);
exit(EXIT_FAILURE);
}else if(error == STRTOUI_UNDERFLOW) {
fputs("The input must be bigger than 0\n", stderr);
exit(EXIT_FAILURE);
}else if(error == STRTOUI_INCONVERTIBLE) {
fputs("The input isn't valid\n", stderr);
exit(EXIT_FAILURE);
}
//prints random numbers in the bounds specified as chars
char lower_bound = 0x20;
char upper_bound= 0x7e;
for(int i = 0; i < len; i++) {
int random = randombytes_uniform(upper_bound);
printf("%c", map(random, 0, upper_bound, lower_bound, upper_bound));
}
printf("\n");
exit(EXIT_SUCCESS);
}