c - Assign random name from file to structure name -
i'm writing program in c end being horse race game. part i'm stuck on generating random names file. i'm using structure horse , linked list store 10 horses. names in file "names". want pick random line in file, go it, copy name current node in linked list, , move on next horse. stops responding when start , returns -1073741819 (0xc0000005)
i'm not experienced using c interact files appreciated.
struct node{ int data; float mult; float payout; int score; struct node *next; char name[20];//where i'm trying store random name. }; void rand_name(node* head, int i){ //a function generate random name list of 3162 names. file* infile; infile = fopen("names","r"); if(infile == null){ printf("error opening names.txt"); exit(exit_failure); } int cnt, j = rand() % 3162;//pick random line copy. char buff[100]; node *tmp = null; tmp = malloc(sizeof(node)); tmp = head; for(cnt = 0; cnt < 1; cnt++){ tmp = tmp->next; //get current node. } cnt = 0; while(cnt < j){ //copy each line until random line copy. fgets(buff, 100, infile); j++; } strcpy(tmp->name, buff); //store last copied line node. return; }
use struct
keyword along name of structure. ie, use struct node
instead of node
in program.
consider using srand()
along rand()
otherwise everytime run program, rand()
return same value.
when strcpy(tmp->name, buff);
after using fgets()
read buff
, remember fgets()
keep newline (\n
) @ end of string. might want remove that.
if trying open file named names.txt
, should write fopen("names.txt","r");
instead of fopen("names","r");
bluepixy pointed out in
tmp = malloc(sizeof(struct node)); tmp = head;
you first allocating memory tmp
, orphaning memory overwriting tmp
head
. use variable store new node.
i think want assign value name
of head
. if so, there's no need create new node.
and felix guo pointed out, use fclose()
close file stream when done working it.
edit: of course, you'll need change j++
in while
loop cnt++
noticed that.
Comments
Post a Comment