【问题标题】:linked list usage to obtain data from file链表用法从文件中获取数据
【发布时间】:2024-04-23 23:50:02
【问题描述】:

我有一个包含电子邮件地址的文本文件。

我想获取这些电子邮件并将其存储在任何数据结构或变量中。 然后我需要从数据结构中随机选择邮件地址。

    #include<stdio.h>
#include<conio.h>
#include <stdlib.h>
#include<string>

struct link_list
{
    char mail[50];
    int counter;
    struct link_list *next;
};
typedef struct link_list node;


void main()
{
FILE *fp ;
char string1[80];
node *head;
int count_length=0;
char *fname = "email.txt";
fp = fopen ( fname, "r" ) ;
char line [ 128 ]; /* or other suitable maximum line size */
int count=0;

while ( fgets ( line, sizeof line, fp ) != NULL ) /* read a line */
{
    count++;
    if(head==NULL)
    {
        head=(node *)malloc(sizeof(node));
        fscanf(fp,"%s",string1);
        strcpy(head->mail,string1);
        head->counter=count;
        head->next=NULL;

    }
    else
    {
    node *tmp = (node *)malloc(sizeof (node));
    fscanf(fp,"%s",string1);
    strcpy(tmp->mail,string1);
    tmp->next = head;
    tmp->counter=count;
    head = tmp;

    }

}

fclose(fp);
fp = fopen ( fname, "r" ) ;

fclose(fp);
//printf("%d",count_length);
getch();
}

我编辑了代码..我收到断言错误

【问题讨论】:

  • 在继续之前,您需要确保对fopen 的调用成功并正确处理任何错误。
  • 我建议将您的代码分开一点:首先编写一个有效的链表实现,然后担心用文件中的内容填充它。该链表的快速提示:如果head 不为NULL,则分配一个新的node,存储您想要的任何数据,将其设置为next 指向head 的指针,然后将head 替换为新的节点。如果您想追加,则需要更多工作,并留作用户练习。 :)

标签: c file-io linked-list


【解决方案1】:

尝试将新条目添加到列表的头部而不是尾部。例如:

node *tmp = malloc(sizeof *tmp);
fscanf(fp, "%s", tmp->mail);
tmp->next = head;
head = tmp;

【讨论】:

  • Thnx...我可以放弃这个链表的想法并使用 fseek() 和 ftell() 以便我可以直接从文件中选择 2 个随机值吗?
【解决方案2】:

如果您执行第一遍查找每个数据起点的偏移量,则可以使用 fseek。

或者您可以使用 The Practice of Programming 中的技巧,通过使用 mod 而不是除法来反转随机测试的概率分布。这使您可以在一次遍历中从未知长度的列表中选择一个随机元素。

此程序使用该技术一次性从字符串中选择和打印一个随机字符。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    char *s = "asequenceofasciivalues";
    int i;
    char o;
    srand(time(NULL));
    o = s[0];
    for (i=0; s[i]; i++)
        if (rand() % (i+1) == 0)
            o = s[i];
    printf("%c\n", o);
    return 0;
}

【讨论】: