C: Reading file with a starting point
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开发者_如何学C), 32, input);
// seed 'rng'...
fclose(input);
}
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.
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
Just fseek
before you read anything!
精彩评论