以下函数从stdin
中读取任意数据,并一次生成一个unsigned int
。如果找到EOF
,则退出。如果文件是无限的(例如/dev/urandom
),它将永远继续下去。我有一个大约95 MiB的文件,它可以产生fread: Bad address
。你知道为什么吗?
unsigned int generator(void)
{
static unsigned int buffer[8192 / sizeof(unsigned int)];
static unsigned int pos; /* where is our number? */
static unsigned int limit; /* where does the data in the buffer end? */
if (pos >= limit) {
/* refill the buffer and continue by restarting at 0 */
limit = fread(buffer, sizeof (unsigned int), sizeof buffer, stdin);
if (limit == 0) {
/* We read 0 bytes. This either means we found EOF or we have
an error. A decent generator is infinite, so this should never
happen. */
if (ferror(stdin) != 0) {
perror("fread"); exit(-1);
}
if (feof(stdin) != 0) {
printf("generator produced eof\n");
exit(0);
}
}
pos = 0;
}
unsigned int random = buffer[pos]; /* get one */
pos = pos + 1;
return random;
}