Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <ctype.h>
- #include <limits.h>
- #include <string.h>
- static void
- trim(char *dst, char *src)
- {
- int i=0, j=0;
- while (isspace(src[i])) {
- i++;
- }
- j = strlen(src) - 1;
- while (isspace(src[j])) {
- j--;
- }
- if (src[j] == ':') j--;
- j++;
- memcpy(dst, src + i, j - i);
- dst[j - i] = '\0';
- }
- int
- main()
- {
- #define HEADERS_MAX 100
- char headers[HEADERS_MAX][LINE_MAX];
- char subheaders[HEADERS_MAX][LINE_MAX];
- char *header_map[LINE_MAX];
- char *subheader_map[LINE_MAX];
- char line[LINE_MAX];
- char header[LINE_MAX];
- int i;
- int subheader_done = 1;
- while (fgets(line, sizeof(line), stdin)) {
- if (islower(line[0])) {
- /* data */
- char key[LINE_MAX];
- int j = 0, start_x = -1;
- subheader_done = 1;
- for (i=0; line[i]; i++) {
- if (!isspace(line[i])) {
- key[j++] = line[i];
- if (start_x < 0) start_x = i;
- } else if (j) {
- char *h = header_map[(start_x + i) / 2];
- char *sh = subheader_map[(start_x + i) / 2];
- key[j] = '\0';
- printf("%s: %s: %s\n", h, sh, key);
- j = 0;
- start_x = -1;
- }
- }
- } else if (isupper(line[0])) {
- /* header */
- subheader_done = 1;
- strncpy(header, line, LINE_MAX);
- } else if (isspace(line[0])) {
- /* sub-header */
- int nhdr = 0, hidx = 0;
- char shdrbuf[LINE_MAX];
- if (subheader_done) {
- memset(subheader_map, 0, sizeof(char *) * LINE_MAX);
- memset(subheaders, 0, HEADERS_MAX * LINE_MAX);
- for (i=0; line[i]; i++) {
- if (!isspace(line[i])) {
- subheader_map[i] = subheaders[nhdr];
- shdrbuf[hidx++] = line[i];
- } else if (hidx) {
- shdrbuf[hidx] = '\0';
- trim(subheaders[nhdr], shdrbuf);
- hidx = 0;
- nhdr++;
- }
- }
- } else {
- char key[LINE_MAX];
- int j = 0, start_x = -1;
- for (i=0; line[i]; i++) {
- if (!isspace(line[i])) {
- key[j++] = line[i];
- if (start_x < 0) start_x = i;
- } else if (j) {
- char *h = subheader_map[(start_x + i) / 2];
- key[j] = '\0';
- /* concat subheaders */
- sprintf(h, "%s %s", h, key);
- j = 0;
- start_x = -1;
- }
- }
- }
- subheader_done = 0;
- } else if (line[0] == '-') {
- /* dashed line, mask for header */
- int nhdr = 0, hidx = 0;
- char hdrbuf[LINE_MAX];
- subheader_done = 1;
- for (i=0; line[i]; i++) {
- if (!isspace(line[i])) {
- header_map[i] = headers[nhdr];
- hdrbuf[hidx++] = header[i];
- } else if (hidx) {
- hdrbuf[hidx] = '\0';
- trim(headers[nhdr], hdrbuf);
- hidx = 0;
- nhdr++;
- }
- }
- } else {
- /* unknown */
- printf("?\n");
- }
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment