Практика 7
#include <stdio.h> | |
#include <stddef.h> | |
#include <expat.h> | |
#define UNUSED(x) (void)(x) | |
#ifdef XML_UNICODE_WCHAR_T | |
# include <wchar.h> | |
# define XML_FMT_STR "ls" | |
#else | |
# define XML_FMT_STR "s" | |
#endif | |
void XMLCALL start_element(void* user_data, const XML_Char* name, const XML_Char **atts) { | |
UNUSED(atts); | |
int* depth = (int*)user_data; | |
for (int i = 0; i < *depth; i++) { | |
printf(" "); | |
} | |
char *f = XML_FMT_STR; | |
printf("%" XML_FMT_STR "\n", name); | |
} | |
void XMLCALL end_element(void *user_data, const XML_Char* name) { | |
UNUSED(name); | |
int* depth = (int*)user_data; | |
(*depth)--; | |
} | |
const int BUF_SIZE = 179; | |
int main() { | |
int ret = 0; | |
FILE* input = fopen("input.xml", "r"); | |
if (input == NULL) { | |
fprintf(stderr, "Failed to open input file\n"); | |
ret = 1; | |
goto ret; | |
} | |
XML_Parser parser = XML_ParserCreate(NULL); | |
char buf[BUF_SIZE]; | |
int done = 0; | |
int depth = 0; | |
XML_SetUserData(parser, &depth); | |
XML_SetElementHandler(parser, start_element, end_element); | |
while (!done) { | |
size_t len = fread(buf, 1, sizeof(buf), input); | |
done = len < sizeof(buf); | |
if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) { | |
fprintf(stderr, "XML error\n"); | |
ret = 1; | |
goto free_parser; | |
} | |
} | |
free_parser: | |
XML_ParserFree(parser); | |
close_file: | |
fclose(input); | |
ret: | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment