2016-09-19 66 views
0

搜索電子郵件,我有一個文本文件,例如「file_with_email.txt」,其中包含以下電子郵件地址:在一個文本文件

crp.edu 
src.net 
abc.edu 

我需要尋找一個電子郵件在給定的文本文件。我的代碼的問題是,當我輸入帶有完整域名的電子郵件地址時,例如,如果我搜索例如「abc.edu」,則它將以「發現電子郵件」的形式返回消息,這是正確的。

但是,如果我輸入的電子郵件地址中包含不完整或部分域名,例如「abc.ed」,作爲給定文件中未包含的輸入,它會輸出與「發現的電子郵件「即使沒有這樣的電子郵件。

此外,在某些情況下,電子郵件會像用戶輸入的「abc.edu.net」一樣。在這種情況下,我的代碼將打印與「找到的電子郵件」相同的輸出,它不包含在給定的文本文件中。我希望有任何幫助解決這個問題。

下面是我到目前爲止已經試過在一個文本文件中搜索電子郵件功能:

int search_mail(char *email) 
{ 
FILE *fp; 
int line = 1; 
int number_of_match = 0; 
char temp[512]; 
char *fname = "/home/file_with_email.txt"; 
    if((fp=fopen(fname, "r"))==NULL) 
    { 
    return(-1); 
    } 

    while(fgets(temp, 512,fp) !=NULL) 
    { 
    fprintf(stdout, "Just read: %s\n", temp); 
     if(strstr(temp, email) !=NULL) 
     { 
     printf("\n The match is found in the file\n "); 
     //printf("\n %s \n", temp); 
     number_of_match++; 
     } 
     //line++; 
    } 

    if(number_of_match == 0) 
     printf("\n No result found"); 

     //close the file if it is open. 

    if(fp) 
     { 
     fclose(fp); 
    } 
    } 
+0

這將有助於縮進代碼正確 –

+0

你不需要'如果(FP)',因爲其始終將是真正 –

+0

'fprintf中(stdout' - 'printf'會做 –

回答

1

建立在@ grek40的答案上,您可以通過mmap()在符合POSIX標準的系統上搜索該文件(請注意,我遺漏了相應的頭文件和所有錯誤檢查以試圖消除代碼上的任何滾動條窗格):

int startsWithWhitespace = 0; 
int endsWithWhitespace = 0; 
int fd = open(filename, O_RDONLY); 
struct stat sb; 
fstat(fd, &sb); 
// size + 1 is needed to ensure the mapped file ends with at least one \0 character 
char *data = mmap(NULL, sb.st_size + 1, PROT_READ, MAP_PRIVATE, fd, 0); 
close(fd); 
char *match = strstr(data, string); 
// found a potential match 
if (match) 
{ 
    // check if it's the first char in the file else check the first character *before* the match 
    if (match == data) 
    { 
     startsWithWhiteSpace = 1; 
    } 
    else 
    { 
     startsWithWhitespace = isspace(*(match - 1)); 
    } 
    // get the character one past the end of the matched string 
    char *end = match + strlen(string); 
    // ensure that the end char is not \0 else the string is at the end of the file 
    if (*end) 
    { 
     endsWithWhitespace = isspace(*end); 
    } 
    else 
    { 
     endsWithWhitespace = 1; 
    } 
} 
... 

最後,如果match非空,都startsWithWhitespaceendsWithWhitespace非零,滿弦已經匹配。

編輯:爲了徹底,您還需要根據標點符號列表來檢查上一個和下一個字符,這些標點符號不會被視爲長字符串的一部分。

假設您要搜索文件多次,這是mmap()的完美使用。搜索文件的代碼是簡單的,您可以將該文件視爲一個長字符串,而不用擔心讀取它的部分內容或如何檢查字符串是否跨越兩個連續的讀取緩衝區。如果你真的調整了IO操作,搜索一個巨大的文件可能會比它慢,但它非常簡單和容易,它可能仍然是最好的方法。

0

看來你基本上要找到一個辦法一個字符串,它用空格包圍或位於文本的開始/結尾處。

因此,您需要的是在搜索文本開始之前跟蹤字符以及可能結果的第一個字符的位置。然後,當您有可能的結果時,檢查它是否位於開頭或結尾,然後在開始之前和結束之後使用isspace(char)檢查字符。如果第一個錯誤匹配(不包括空格),則還需要稍後檢查real匹配的字符串。

您當前的方法存在的另一個問題是,您可能會從前512個字符開始,然後結束後512個字符。你目前在這樣的位置找不到結果。

相關問題