mardi 30 décembre 2014

Generate random number for atribute in struct

I have a struct called drug, and i want to generate random numbers for the atributes minimal_quantity and quantity. But every time i run the code, i get the same numbers on these two atributes, for all drugs that are generated.


My struct is defined this way:



struct drug{
int code;
char name[25];
int minimal_quantity;
int quantity;};


And the method for generating drugs is this:



load_drugs_file(){
int i;

for(i=0;i<=50;i++){

if ((fp=fopen("drugs.dat","a+"))==NULL){
printf("Error: impossible to open the file. \n");
exit(1);
}

struct drug m;
srand(time(NULL));
int r1 = rand() % 500; /* random int between 0 and 499 */
int r2 = rand() % 1000; /* random int between 0 and 999 */

m.code=i;
strcpy(m.name,"A");
m.minimal_quantity=r1;
m.quantity=r2;

fwrite(&m,sizeof(m),1,fp);

fclose(fp);
}}


Any suggestions?





Aucun commentaire:

Enregistrer un commentaire