[英]E-mail header extraction using C substring program gives wrong output. Why?
我的目標是從包含電子郵件標題信息的文本文件中提取主題字段的內容,然后將主題字段中的內容復制到新的文本文件中。 但是程序給出了錯誤的輸出。 下面是我在C中創建的程序( f1.c
)。 我省略了程序的頭文件,可變的delaration部分:
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?
編譯並運行此程序后:
princy@PRINCY:~/minipjt$ cc f1.c
princy@PRINCY:~/minipjt$ ./a.out spam.txt b2.c
我得到的輸出文件( b2.c
)包含:
are you
good?
輸出文件實際上應該只包含下面給出的行:
get that new car 8434
更正:
如果您使用面向行的輸入而不是面向單詞的輸入,這將使事情變得容易。 例如getline
或fgets
(我更喜歡getline
)。 使用面向行的輸入來完整捕獲每一行,可以為Subject:解析文件,並更輕松地處理結果字符串。
例如,嘗試:
# 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.