c - 将文件中的随机名称分配给结构名称

标签 c

我目前正在用 C 语言编写一个程序,该程序最终将成为一个赛马游戏。我所坚持的部分是从文件生成随机名称。我正在使用马的结构和存储 10 匹马的链接列表。这些名称位于文件“Names”中。我想在文件中随机选择一行,转到它,将名称复制到链表中的当前节点,然后转到下一匹马。目前,当我启动它时它停止响应并返回 -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;
}

最佳答案

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

考虑将 srand()rand() 一起使用,否则每次运行程序时,rand() 可能会返回相同的值.

当您在使用 fgets() 读入 buff 后执行 strcpy(tmp->name, buff); 时,请记住 fgets() 将保留换行符 (\n) 位于字符串末尾。您可能想删除它。

如果您尝试打开名为 Names.txt 的文件,则应编写 fopen("Names.txt","r"); 而不是 fopen("名称","r");

BLUEPIXY指出在

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

您首先将内存分配给tmp,然后通过用head覆盖tmp来孤立该内存。 使用另一个变量来存储新节点。

我认为您只想为 headname 分配一个值。如果是这样,则无需创建新节点。

Felix Guo指出,当您使用完文件流后,请使用 fclose() 关闭文件流。

编辑: 当然,您需要将 while 循环中的 j++ 更改为 cnt++,但您已经注意到了这一点。

关于c - 将文件中的随机名称分配给结构名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45315484/

相关文章:

c - 文件描述符 : troubles in storing a read int value into a variable

c - 为什么 fork() 返回该组合中所有可能的输出?

c - 动态地从文本文件中读取一行

c - 为什么 valgrind 不检测数组中的多余元素

c - 为什么我的 C 程序崩溃

c - 使用双指针时的奇怪行为

在 C 中使用 popen 捕获 tshark 标准输出

c - 我在这个循环中做错了什么?

c - "Private"C 中带有 const 的结构成员

c++ - __attribute__((constructor)) 究竟是如何工作的?