【发布时间】: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