Anonymous avatar Anonymous committed 67e0f30

Demo: changed to read from '.js' file

Comments (0)

Files changed (1)

 
 #define NUM_TOKENS 20
 
-static void json_dump_obj(jsontok_t *obj, const unsigned char *js) {
+static void json_dump_obj(jsontok_t *obj, const char *js) {
 	size_t len;
 
-	printf("[%d,%d]", obj->start, obj->end);
-	len = (size_t) (obj->end - obj->start);
+	if (obj->end < 0 || obj->start < 0) {
+		return;
+	}
+
+	len = obj->end - obj->start;
+
+	printf("[%d,%d]\t", obj->start, obj->end);
 
 	char *type;
 	switch (obj->type) {
 		case JSON_OTHER:
-			type = "other";
+			type = "(?)";
 			break;
 		case JSON_NUMBER:
-			type = "number";
+			type = "(N)";
 			break;
 		case JSON_STRING:
-			type = "string";
+			type = "(S)";
 			break;
 		case JSON_ARRAY:
-			type = "array";
+			type = "(A)";
 			break;
 		case JSON_OBJECT:
-			type = "object";
+			type = "(O)";
 			break;
 	}
 
-	printf(" %s ", type);
+	printf("%s ", type);
 
-	if (len > 0) {
-			char *s = strndup((const char *) &js[obj->start], len);
-			printf("%s", s);
-			free(s);
-	}
-	printf("\n");
+	char *s = strndup((const char *) &js[obj->start], len);
+	printf("%s\n", s);
+	free(s);
 }
 
-int main(void) {
+int main(int argc, char *argv[]) {
 	int i;
 	jsontok_t tokens[NUM_TOKENS];
+	FILE *f;
+	int filesize = 0;
+	char *js = NULL;
 
-	const unsigned char *js = (unsigned char *)
-		"{"
-			"\"foo\": \"bar\","
-			"\"bar\": [1,2, 3],"
-			"\"obj\": { \"true\": false}"
-		"}";
+	if (argc != 2) {
+		fprintf(stderr, "Usage: ./demo <file.js>\n");
+		exit(EXIT_SUCCESS);
+	}
 
-	jsmn_parse(js, tokens, NUM_TOKENS, NULL);
+	f = fopen(argv[1], "r");
+	if (f == NULL) {
+		fprintf(stderr, "Failed to open file `%s`\n", argv[1]);
+		exit(EXIT_FAILURE);
+	}
+
+	while (1) {
+		int r;
+		char buf[BUFSIZ];
+		r = fread(buf, 1, BUFSIZ, f);
+		if (r <= 0) {
+			break;
+		}
+		js = (char *) realloc(js, filesize + r);
+		if (js == NULL) {
+			fprintf(stderr, "Cannot allocate anough memory\n");
+			fclose(f);
+			exit(EXIT_FAILURE);
+		}
+		memcpy(js + filesize, buf, r);
+		filesize += r;
+	}
+
+	fclose(f);
+
+	jsmn_parse((unsigned char *) js, tokens, NUM_TOKENS, NULL);
 
 	for (i = 0; i<NUM_TOKENS; i++) {
 		json_dump_obj(&tokens[i], js);
 	}
 
+	free(js);
+
 	return 0;
 }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.