2014-09-27 10 views
0

我的目標是從包含電子郵件標題信息的文本文件中提取主題字段內容,並將主題字段中的內容複製到新的文本文件中。但該程序給出了錯誤的輸出。我在C中創建的程序(f1.c)在下面給出。我遺漏了我的計劃的頭,可變delaration部分:使用C子串程序提取電子郵件頭會導致錯誤輸出。爲什麼?

ifp = fopen(argv[1],"r"); 
ofp = fopen(argv[2],"w"); 

if (ifp==NULL)  
{  
    printf("\nFile cannot be opened\n"); 
    return; 
} 
else 
{ 
    while(fscanf(ifp,"%s",buf)!=EOF) 
    { 
     printf("%s\n",buf); 
     if (strstr(buf,"Subject:")==0) 
     { 
      //fprintf(ofp,"%s","hai"); 
      fscanf(ifp,"%[^\n]s",buf); 
      fprintf(ofp,"%s",buf); 
     } 
     else 
     { 
       fgets(buf,15,ifp); 
      } 
     } 
    } 
    fclose(ofp); 
    fclose(ifp); 
} 

這裏是我使用的輸入文件:(spam.txt.

To:hhhhgdg 
Subject:get that new car 8434 
hi,how are you 
keeping good? 

編譯後運行此程序:

[email protected]:~/minipjt$ cc f1.c 
[email protected]:~/minipjt$ ./a.out spam.txt b2.c 

我得到的輸出文件包含:

are you 
good? 

輸出文件實際上應該只包含線如下:

get that new car 8434 

回答

3

更正:

這將使事情變得更容易,如果你使用的不是字處理面向行輸入面向輸入。例如getlinefgets(我更喜歡getline)。使用面向行的輸入來捕獲每行的全部內容,使文件解析爲主題:並且處理結果字符串變得更容易。

例如,嘗試:

# include <stdio.h> 
# include <string.h> 

int main (int argc, char **argv) { 

    if (argc < 3) { 
     fprintf (stderr, "Error: insufficient input. Usage: %s input_file output_file\n", 
       argv[0]); 
     return 1; 
    } 

    FILE *ifp = fopen(argv[1],"r"); 
    FILE *ofp = fopen(argv[2],"w"); 

    char *buf = NULL; /* forces getline to allocate space for buf */ 
    ssize_t read = 0; 
    size_t n = 0; 
    char *ptr = NULL; 

    if (ifp==NULL)  
    {  
     printf("\nFile cannot be opened\n"); 
     return 1; 
    } 
    else 
    { 
     while ((read = getline (&buf, &n, ifp)) != -1) 
     { 
      printf("%s\n",buf); 

      if ((ptr=strstr(buf,"Subject:")) != 0) 
       fprintf(ofp,"%s",ptr);  /* use (ptr + 9) to trim 'Subject:` away */ 
     } 
    } 

    if (buf)  /* free memory allocated by getline for buf */ 
     free (buf); 
    fclose(ofp); 
    fclose(ifp); 

    return 0; 
} 

如果你的目標是後主題只捕獲行的內容:,那麼你可以簡單地前進指針ptr的空間後,繼:ptr += 9;,然後輸出到你的文件。

讓我知道如果您有任何問題。


附錄 - 行主題後:

爲了獲得主題行後,你可以簡單地繼續以同樣的if塊和讀取再次使用getline下一行。用現有的代碼塊代替:

  if ((ptr=strstr(buf,"Subject:")) != 0) { 
       fprintf(ofp,"%s",ptr); /* use (ptr + 9) to trim 'Subject:` away */ 

       /* get line after Subject */ 
       if ((read = getline (&buf, &n, ifp)) != -1) 
        fprintf(ofp,"Line after Subject: %s",buf); 
      } 
+1

它解決了。我需要在subject.By更改ptr到ptr + 8後,我可以得到所需的答案。 – PRINCY 2014-09-27 09:10:40

+0

很高興爲你效勞。在'主題:'之後增加**補充**。讓我知道,如果這是你所需要的。 – 2014-09-27 14:59:49

+0

我需要將一個文本文件中的主題(可以有多行)提取到另一個文本文件中的電子郵件的其他頭字段,最後將正文轉換爲第三個文本文件。在這個程序中應該做什麼修改? – PRINCY 2014-09-30 04:52:33

相關問題