#include #include #include #include #include "yxmllib.h" #define BUFSIZE 8096 typedef struct buffer { int len; char *buffer; } buffer; buffer *buffer_new() { buffer *buf = malloc(sizeof(buffer)); buf->buffer = malloc(BUFSIZE); if (!buf || !buf->buffer) { fprintf(stderr, "Could not allocate memory for buffer struct.\n"); exit(1); } buf->len = 0; return buf; } buffer *buffer_reset(buffer *buf) { buf->buffer = memset(buf->buffer, 0, BUFSIZE); buf->len = 0; return buf; } buffer *buffer_append(buffer *buf, char *data) { for (int i = 0; data[i]; i++) { buf->buffer[buf->len] = data[i]; buf->len++; } return buf; } int process(char *fn, yxml_t *state) { size_t filelen; char *parsebuffer; int intitlegroup, inarticletitle; buffer *contentbuf; FILE* f = fopen(fn, "rb"); if (!f) { fprintf(stderr, "Could not open %s.", fn); perror("Error:"); return 1; } // get file size fseek(f, 0L, SEEK_END); filelen = ftell(f); rewind(f); parsebuffer = calloc(1, filelen+1); if (!parsebuffer) { fprintf(stderr, "Could not allocate memory for file %s.\n", fn); fclose(f); return 1; } if (fread(parsebuffer, filelen, 1 , f) != 1) { fprintf(stderr, "Could not read file into memory for file %s.\n", fn); free(parsebuffer); fclose(f); return 1; } fclose(f); intitlegroup = 0; inarticletitle = 0; contentbuf = buffer_new(); yxml_init(state, state+1, BUFSIZE); for (; *parsebuffer; parsebuffer++) { yxml_ret_t r = yxml_parse(state, *parsebuffer); if(r < 0) { printf("Parsing error at %s: line %u, byte %lu, offset %lu\n", fn, state->line, state->byte, state->total); return 1; } switch(r) { case YXML_ELEMSTART: if (!strcmp(state->elem, "title-group")) { intitlegroup = 1; } else if (!strcmp(state->elem, "article-title") && intitlegroup) { printf("%s: ", state->elem); inarticletitle = 1; } break; case YXML_CONTENT: if (inarticletitle) { buffer_append(contentbuf, state->data); } break; case YXML_ELEMEND: if (inarticletitle && !strcmp(state->elem, "title-group")) { inarticletitle = 0; intitlegroup = 0; printf("%s\n", contentbuf->buffer); buffer_reset(contentbuf); } break; } } return 0; } int main(int argc, char *argv[]) { yxml_t *state = malloc(sizeof(yxml_t) + BUFSIZE); for (int i = 1; i < argc; i++) { process(argv[i], state); } return 0; }