我有一个带有电子邮件地址的文本文件。链接列表用法从文件中获取数据
我想获得这些电子邮件并将其存储在任何数据结构或变量中。 然后,我需要从数据结构中随机选择邮件地址。
#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();
}
我编辑的code..i我得到断言错误
在继续之前,您需要确保对'fopen`的调用成功并正确处理任何错误。 – 2011-01-30 09:37:35
我建议将代码分开一点:首先编写一个可以工作的链接列表实现,然后__担心从文件中填充内容。对这个链表的快速提示:如果head不是NULL,则分配一个新的`node`,存储你想要的任何数据,将它设置为`next`指向`head`,然后用你的new替换`head`节点。如果你想追加,它是更多的工作,并留下作为用户的锻炼。 :) – sarnold 2011-01-30 09:39:33