1

Still having trouble generating random seeds. Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

double dev_random_seed(){
  double randval;
  FILE* f;

  f = fopen("/dev/random", "r");
  if(f == NULL){
    fprintf(stderr, "WARNING: Failed to open /dev/random. Random seed defaults to 1. \n");
    return 1;
  }

  fread(&randval, sizeof(double), 1, f);
  fclose(f);
  return randval;
}

int main(int argc, char** argv){
  double arse = dev_random_seed();

  printf("errno: %i\n",errno);
}

The output of which is:

errno: 22

which is EINVAL. Can't spot the mistake , I suck at c.

4

2 回答 2

1

Don't check errno unless you have an error.
It may be that a library sets a value of errno in advance because it represents a cause that a later part won't know IF the later part has an error (sorry that could be clearer)

See https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=6619179

于 2012-08-03T15:26:38.147 回答
0

You should not check for errno if there were no error. To notify main that an error has occured, you may use the following code:

if (fread (&randval, sizeof(double), 1, f)<0) return NAN;

and, correspondingly, in main:

if (isnan (arse)) printf ("Error has occured: %i\n",errno);
于 2012-08-03T15:27:42.787 回答