我有一个包含电子邮件地址的文本文件。
我想获取这些电子邮件并将其存储在任何数据结构或变量中。 然后我需要从数据结构中随机选择邮件地址。
#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();
}
我编辑了代码..我正在收到断言错误
答案 0 :(得分:2)
尝试将新条目添加到列表的头部而不是尾部。例如:
node *tmp = malloc(sizeof *tmp);
fscanf(fp, "%s", tmp->mail);
tmp->next = head;
head = tmp;
答案 1 :(得分:0)
如果你做了第一遍来找到每个数据开头的偏移量,你可以使用fseek。
或者您可以使用编程实践中的技巧,通过使用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;
}