Created
March 24, 2019 20:14
-
-
Save benthepoet/f0f6b66d3a425b41bf956f0df9abd7fa to your computer and use it in GitHub Desktop.
Parsing S-expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctype.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define DATA_FILE "data.lisp" | |
struct Node { | |
char *data; | |
struct Node *next; | |
struct Node *children; | |
}; | |
void read_children(FILE *fp, struct Node **head); | |
int main(int argc, char *argv[]) { | |
FILE *fp; | |
fp = fopen(DATA_FILE, "r"); | |
struct Node *root; | |
read_children(fp, &root); | |
fclose(fp); | |
return 0; | |
} | |
void read_children(FILE *fp, struct Node **head) { | |
struct Node *node; | |
int c; | |
char buffer[32]; | |
while ((c = fgetc(fp)) != EOF) { | |
if (c == '(') { | |
node = calloc(1, sizeof(struct Node)); | |
read_children(fp, &node->children); | |
node->next = *head; | |
*head = node; | |
} | |
else if (c == ')') { | |
break; | |
} | |
else if (!isspace(c)) { | |
ungetc(c, fp); | |
if (c == '"') { | |
fscanf(fp, "\"%31[^\"]\"", buffer); | |
} else { | |
fscanf(fp, "%31[^() ]", buffer); | |
} | |
node = calloc(1, sizeof(struct Node)); | |
node->data = calloc(strlen(buffer), sizeof(char)); | |
strcpy(node->data, buffer); | |
node->next = *head; | |
*head = node; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment