有一个XML文件,我必须识别,存储和打印其中的唯一标签。
示例XML文件:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</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..
也出现分段错误。
答案 0 :(得分:0)
这只解决了您问题中的一个分段错误:
你必须给strcmp一个字符串,你不能只给字符(res[0]
)。但既然你不需要比较字符串,为什么不比较第一个字符(res[0]=='/')
?