我有一個帶有電子郵件地址的文本文件。鏈接列表用法從文件中獲取數據
我想獲得這些電子郵件並將其存儲在任何數據結構或變量中。 然後,我需要從數據結構中隨機選擇郵件地址。
#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