|
-
January 29th, 2003, 12:11 AM
#1
How to write an usigned value to file accurately
I would like to find a way to store an unsigned value most accurately so that I could reuse it when I seed my random number generator. Currently, I am writing it to a file. However I realise that what is stored will be dependent on the conversion specifier. Which conversion specifier will ensure the most accurate storage?
Code:
unsigned seedtime;
seedtime=(unsigned)time( NULL );// This will be the seed which I //require
appendfile(seedtime);
//code for appendfile
void appendfile( unsigned count)
{
FILE *cfPtr;
if ((cfPtr= fopen("updx.txt","a"))== NULL )
printf ("File could not be opened\n");
else{
fprintf(cfPtr,"%u\n",count);
}
fclose(cfPtr);
}
Currently I am using %u but wonder if there is any other better and more accurate coversion specifier.
Is there any other method to store my unsigned seedtime so that I can use it again when I run my program?
Another question regards my fopen command . Is there any way I can change the directory in which updx.txt can be stored? Currently it is stored in my working directory but I would like to change it to my specification.
Thanx a lot in advance for any help.
-
January 29th, 2003, 02:07 AM
#2
1) Save the data to a binary file. Then there is no conversion to be done.
unsigned int nData;
//open the file in binary mode
fwrite(&nData, sizeof(nData), 1, pFile);
2) You can specify the full path like:
fopen("c:\\temp\\updx.txt","a");
Dan
-
January 29th, 2003, 02:50 AM
#3
WeeBeng: Why would you want to store your seed in a file?
Just seed the random generator once with the current time will do.
-
January 29th, 2003, 03:52 AM
#4
I understand that I only need seed a random number generator once to get a good set of random numbers.
Actually I want to keep seeding the random number generator with the same seed because I want the use the same set of random numbers generated as data to test different sets of functions I have written and compare their results. As the programme will run for a long time for each function, it is preferable that I actually run them at different times using the same data.
Thanks for all the help . Finally managed to get what I want .
Sample working code as follows in case anybody wants to do a similar thing in future.
Code:
void appendfile(unsigned number)
{
FILE *cfPtr;
if ((cfPtr= fopen("c:\\updx","wb"))== NULL )
printf ("File could not be opened\n");
else{
fwrite(&number, sizeof(number), 1, cfPtr);
}
fclose(cfPtr);
}
unsigned readfile( char *string)
{
FILE *cfPtr;
unsigned number;
if ((cfPtr= fopen(string,"rb"))== NULL )
printf ("File could not be opened\n");
else{
fread(&number,sizeof(number),1,cfPtr);
}
fclose(cfPtr);
return number;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|