gpt4 book ai didi

c - 读取 XML 文件并使用 C 打印标签

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

有一个 XML 文件,我必须识别、存储和打印其中存在的唯一标签。

示例 XML 文件:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

我需要将 note、to、from、heading、body 等标签存储在一个数组中,然后打印出来。

下面是我试过的代码,但在检查和删除结束标记中的 / 以识别重复标记时遇到问题。

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

/*Max number of characters to be read/write from file*/
#define MAX_CHAR_FOR_FILE_OPERATION 1000000

int read_and_show_the_file()
{
FILE *fp;
char text[MAX_CHAR_FOR_FILE_OPERATION];
int i;

fp = fopen("/tmp/test.txt", "r");

if(fp == NULL)
{
printf("File Pointer is invalid\n");
return -1;
}
//Ensure array write starts from beginning
i = 0;

//Read over file contents until either EOF is reached or maximum characters is read and store in character array
while( (fgets(&text[i++],sizeof(char)+1,fp) != NULL) && (i<MAX_CHAR_FOR_FILE_OPERATION) ) ;
const char *p1, *p2, *temp;
temp = text;

while(p2 != strrchr(text, ">"))
{
p1 = strstr(temp, "<");
p2 = strstr(p1, ">");
size_t len = p2-p1;
char *res = (char*)malloc(sizeof(char)*(len));
strncpy(res, p1+1, len-1);
res[len] = '\0';
printf("'%s'\n", res);

temp = p2 + 1;
}

fclose(fp);

return 0;
}

main()
{
if( (read_and_show_the_file()) == 0)
{
printf("File Read and Print is successful\n");
}
return 0;
}

我还尝试了 strcmp 检查 if(strcmp(res[0],"/")==0) 的值来检查结束标记,但没有工作,显示段错误. C 上没有示例。请查看并提出建议。

下面是输出:

'note'
'to'
'/to' //(Want to remove these closing tags from output)
'from'
'/from' //(Want to remove these closing tags from output)
and so on..

段错误也发生了。

最佳答案

这仅解决了您问题中的一个段错误:

你必须给strcmp提供字符串,不能只给字符(res[0])。但是既然你不需要比较字符串,为什么不只比较第一个字符 (res[0]=='/')?

关于c - 读取 XML 文件并使用 C 打印标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43061404/

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