问题
i have a text file with emails addresses present.
i want to obtain those emails and store it in any data structure or variable. Then i need to select mail address from random from the data structure.
#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();
}
I edited the code..i am getting assertion error
回答1:
Try adding new entries to the head of the list instead of the tail. For example:
node *tmp = malloc(sizeof *tmp);
fscanf(fp, "%s", tmp->mail);
tmp->next = head;
head = tmp;
回答2:
You can use fseek if you do a first pass to find the offsets for the start of each datum.
Or you can use the trick from The Practice of Programming where you invert the probability distribution of the random test by using mod instead of divide. This lets you select a random element from a list of unknown length in just one pass.
This program uses the technique to select and print a random character from a string in one pass.
#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;
}
来源:https://stackoverflow.com/questions/4842166/linked-list-usage-to-obtain-data-from-file