/* Test program by Jeff Sadowski on how to use initstate and setstate
This program helped me figure them out through experimentation. */
#include<time.h>/*time*/
#include<stdio.h>/*fopen printf fread fwrite fclose*/
#include<stdlib.h>/*random*/
#include<unistd.h>/*getopt*/
#include<errno.h>/*errno*/
#include<string.h>/*strerror*/
enum load_save {neither=0,load,save};
const int STATE_SIZE=256;
int main(int argc,char **argv)
{
unsigned int seed=1;
FILE *fp=NULL;
char state[STATE_SIZE];
char saved[STATE_SIZE];
int x;
enum load_save y=neither;
initstate(seed,state,STATE_SIZE);
switch(getopt(argc,argv,"l:s:"))
{
case 'l':/*load*/
fp=fopen(optarg,"r");
y=load;
break;
case 's':/*save*/
fp=fopen(optarg,"w");
y=save;
break;
default:
if(argc>1)
{
printf("Invalid usage: %s [-l loadfile]||[-s savefile]",argv[0]);
return -1;
}
}
if(y&&fp==NULL)
{
fprintf(stderr,"fopen failed on %s:%s\n",optarg,strerror(errno));
return -1;
}
for(x=0;x<200;x++)
{/* offset it from the seed by an arbitrary number in this case 200
so know I can pick up where I left off */
setstate(state);
random();
}
/* how to save the current state this took me some time to
learn it was not documented well at all. */
memcpy(saved,setstate(state),STATE_SIZE);
if(y==save)
{
fwrite(saved,1,STATE_SIZE,fp);
}
if(y!=load)
{
for(x=0;x<5;x++)
{/* print the next 5 random sequence of numbers */
setstate(state);
printf("%i\n",random()%10);
}
}
else
{
fread(saved,1,STATE_SIZE,fp);
}
if(y!=save)
{
setstate(saved);/* load the saved state*/
for(x=0;x<5;x++)
{/* this should start on the same place
in the sequence we saved it at */
setstate(saved);
printf("%i\n",random()%10);
}
}
if(y)
{
fclose(fp);
}
return 0;
}