2011-01-30 19 views
-1

我有一個帶有電子郵件地址的文本文件。鏈接列表用法從文件中獲取數據

我想獲得這些電子郵件並將其存儲在任何數據結構或變量中。 然後,我需要從數據結構中隨機選擇郵件地址。

#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我得到斷言錯誤

+0

在繼續之前,您需要確保對'fopen`的調用成功並正確處理任何錯誤。 – 2011-01-30 09:37:35

+1

我建議將代碼分開一點:首先編寫一個可以工作的鏈接列表實現,然後__擔心從文件中填充內容。對這個鏈表的快速提示:如果head不是NULL,則分配一個新的`node`,存儲你想要的任何數據,將它設置爲`next`指向`head`,然後用你的new替換`head`節點。如果你想追加,它是更多的工作,並留下作爲用戶的鍛鍊。 :) – sarnold 2011-01-30 09:39:33

回答

2

嘗試添加新條目到列表中,而不是尾部的頭部。例如:

node *tmp = malloc(sizeof *tmp); 
fscanf(fp, "%s", tmp->mail); 
tmp->next = head; 
head = tmp; 
0

如果您第一次爲每個數據的開始找到偏移量,您可以使用fseek。

或者你可以使用編程實踐中的技巧,通過使用mod而不是divide來反轉隨機測試的概率分佈。這讓您只需一次從一個未知長度列表中選擇一個隨機元素。

該程序使用該技術從一個字符串中選擇並打印一個隨機字符。

#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; 
}