r/C_Programming • u/Parking_Impress539 • 1h ago
Review Help with seed generation for RNG.
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef float f32;
typedef double f64;
i8 RANDOM_SEED(){
static i8 seed = 0;
static i8 init = 0;
if (init) return seed;
FILE *pF = fopen("SEED_FILE", "rb");
if (pF) {
fread(&seed, sizeof(i8), 1, pF);
}
else {
i8 created = 0;
srand((u32)time(NULL));
seed = (i8)(rand() % 246 - 128);
do {
pF = fopen("SEED_FILE", "wb");
if(pF){
fwrite(&seed, sizeof(i8), 1, pF);
created = 1;
}
} while(created != 1);
}
fclose(pF);
pF = NULL;
init = 1;
return seed;
}I'm trying to make a seed generator. How it works: you call the function and it creates a seed file with a raw binary value inside it that cannot be read by a human. The program reads it and produces a seed that will always be the same for one computer but will vary from computer to computer. I will use it to make a random number generator whose output is constant on the same machine but differs across machines. Can you tell me if this is efficient, or am I overdoing, underdoing, or overcomplicating things? And also I want to make it memory efficient.
I am making this to clarify my concept on file reading - writing and RNG.
3
u/tstanisl 53m ago
8bit is not especially great amount of entropy to work with. Good quality generators use thousands. For just statistically correct noise generators (which rand() IS NOT) 64 bit is usually enough. I don't see the point of storing to a file. Just dump it to logs and add an option for user to pass it explicitly. Otherwise use date or /dev/random.
1
u/MFFVD 56m ago
while(created != 1)? that seems a bit strange for errorhandling
1
u/mjmvideos 46m ago
Explain your thinking on “cannot be read by a human”. Any file in a file system can be read by a human.
1
u/Ordinary-Pirate7852 58m ago
do {
pF = fopen("SEED_FILE", "wb");
if(pF){
fwrite(&seed, sizeof(i8), 1, pF);
created = 1;
}
} while(created != 1);
why are we looping here
feels kinda wrong calling fopen on an already open file (i might be wrong on this)
2
u/No_External_4869 18m ago