2017-07-26 61 views
0

我目前正在用C编写一个程序,最终成为赛马游戏。我坚持的部分是从文件生成随机名称。我正在使用一匹马和一个链表来存储10匹马。名字在文件“名称”中。我想在文件中选择一个随机行,转到它,将名称复制到链接列表中的当前节点,然后转到下一匹马。目前它只是停止响应,当我启动它,并返回-1073741819(0xC0000005)从文件中指定结构名称的随机名称

我不是非常有经验的使用C与文件进行交互,所以任何帮助非常感谢。

struct node{ 
    int data; 
    float mult; 
    float payout; 
    int score; 
    struct node *next; 
    char name[20];//Where I'm trying to store the random name. 
}; 


void rand_name(node* head, int i){ 
    //A function to generate a random name from a 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 a random line to copy. 
    char buff[100]; 

    node *tmp = NULL; 
    tmp = malloc(sizeof(node)); 
    tmp = head; 

    for(cnt = 0; cnt < 1; cnt++){ 
     tmp = tmp->next; //Get to the current node. 
    } 
    cnt = 0; 
    while(cnt < j){ 
     //Copy each line until you get to the random line to copy. 
     fgets(buff, 100, infile); 
     j++; 
    } 

    strcpy(tmp->name, buff); //Store the last copied line into the node. 

    return; 
} 
+1

'j ++;' - >'cnt ++','tmp = malloc(sizeof(node)); tmp = head;':'tmp'由'head'覆盖。 – BLUEPIXY

+2

你知道文件中有3162行吗?你怎么知道?如果文件被编辑会怎么样?如果文件中没有多少行,代码应该做什么? –

+0

停止响应,大概是因为它忙于溢出'j',然后它用fgets读取文件末尾; fgets返回NULL ... –

回答

0

使用struct关键字以及您的结构名称。 即在您的程序中使用struct node而不仅仅是node

考虑使用srand()以及rand()否则每次运行程序时,rand()可能会返回相同的值。

当你使用fgets()读入buff后做strcpy(tmp->name, buff);,请记住,fgets()将保持换行符 (\n)在字符串的结尾。你可能想要删除它。如果你试图打开一个名为Names.txt的文件,你应该写,而不是

fopen("Names.txt","r");fopen("Names","r");

BLUEPIXY指出,在

tmp = malloc(sizeof(struct node)); 
tmp = head; 

你第一次分配内存tmp,然后成为孤儿内存通过覆盖tmphead。 使用另一个变量来存储新节点。

我想你只是想分配一个值为namehead。如果是这样,则不需要创建新节点。

而如Felix Guo指出,使用fclose()关闭您的文件流,当你完成它的工作。

编辑: 当然,你需要在while循环改变j++cnt++但你已经注意到了。