gpt4 book ai didi

c - 使用 C 子字符串程序提取电子邮件 header 会给出错误的输出。为什么?

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:24 25 4
gpt4 key购买 nike

我的目标是从包含电子邮件标题信息的文本文件中提取主题字段内容,并将主题字段中的内容复制到新的文本文件中。但是程序给出了错误的输出。下面给出了我在 C 中创建的程序 (f1.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?

编译并运行该程序后:

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

最佳答案

更正:

如果您使用line-oriented 输入而不是word-oriented 输入,事情会变得更容易。例如 getlinefgets(我更喜欢 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;
}

如果您的目标是只捕获 Subject: 之后的行的内容,那么您可以简单地将指针 ptr 前进到 之后的空格之后:ptr += 9;,然后输出到你的文件。

如果您有任何问题,请告诉我。


附录 - 主题后一行:

要获取主题后的行,您可以简单地继续相同的 if block 并再次使用 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);
}

关于c - 使用 C 子字符串程序提取电子邮件 header 会给出错误的输出。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com