tags:

views:

60

answers:

3

A simple question but I can't find the answer in my book. I want to read a binary file to seed a random number generator, but I don't want to seed my generator with the same seed each time I call the function, so I will need to keep a variable for my position in the file (not a problem) and I would need to know how to read a file starting a specific point in the file (no idea how). The code:

void rng_init(RNG* rng) {
  // ...

  FILE *input = fopen("random.bin", "rb");
  unsigned int seed[32];
  fread(seed, sizeof(unsigned int), 32, input);

  // seed 'rng'...

  fclose(input);
}
+1  A: 

Just fseek before you read anything!

Autopulated
+3  A: 

You can use ftell() to read the current position of the file, and fseek() to jump to a specific position, e.g.

long cur = ftell(f);
fseek(f, 0, SEEK_START);   // jump to beginning
fread(...)
fseek(f, cur, SEEK_START); // returning to previous location.
KennyTM
Beware that on some operating systems (OpenVMS) the value which comes from ftell() and goes to fseek() is a magic cookie and should not be inspected or operated on. This doesn't apply to reasonable operating systems like Linux where the value is the byte offset from the beginning of file.
wallyk
+2  A: 

You can use fseek to move to a random position within a file.

fseek takes a third parameter that tells what the position is relative to.

SEEK_SET - the absolute position from the start of the file
SEEK_CUR - the position relative to where you currently are in the file
SEEK_END - the position relative to the end of the file
R Samuel Klatchko