KDECore
krandom.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "krandom.h"
00023
00024 #include <stdlib.h>
00025 #include <unistd.h>
00026 #include <stdio.h>
00027 #include <time.h>
00028 #include <sys/time.h>
00029 #include <fcntl.h>
00030 #include <kde_file.h>
00031
00032 int KRandom::random()
00033 {
00034 static bool init = false;
00035 if (!init)
00036 {
00037 unsigned int seed;
00038 init = true;
00039 int fd = KDE_open("/dev/urandom", O_RDONLY);
00040 if (fd < 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed))
00041 {
00042
00043 srand(getpid());
00044 seed = rand()+time(0);
00045 }
00046 if (fd >= 0) close(fd);
00047 srand(seed);
00048 }
00049 return rand();
00050 }
00051
00052 QString KRandom::randomString(int length)
00053 {
00054 if (length <=0 ) return QString();
00055
00056 QString str; str.resize( length );
00057 int i = 0;
00058 while (length--)
00059 {
00060 int r=random() % 62;
00061 r+=48;
00062 if (r>57) r+=7;
00063 if (r>90) r+=6;
00064 str[i++] = char(r);
00065
00066 }
00067 return str;
00068 }