Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c - linked list usage to obtain data from file

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...