Skip to content

Instantly share code, notes, and snippets.

@benthepoet
Created March 24, 2019 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benthepoet/f0f6b66d3a425b41bf956f0df9abd7fa to your computer and use it in GitHub Desktop.
Save benthepoet/f0f6b66d3a425b41bf956f0df9abd7fa to your computer and use it in GitHub Desktop.
Parsing S-expression
#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