我目前正在用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;
}
'j ++;' - >'cnt ++','tmp = malloc(sizeof(node)); tmp = head;':'tmp'由'head'覆盖。 – BLUEPIXY
你知道文件中有3162行吗?你怎么知道?如果文件被编辑会怎么样?如果文件中没有多少行,代码应该做什么? –
停止响应,大概是因为它忙于溢出'j',然后它用fgets读取文件末尾; fgets返回NULL ... –