Codebase list libmawk / 70499808-c2b9-4be2-ae11-0ab4b3a1a115/main src / example_apps / 15_get_array / app.c
70499808-c2b9-4be2-ae11-0ab4b3a1a115/main

Tree @70499808-c2b9-4be2-ae11-0ab4b3a1a115/main (Download .tar.gz)

app.c @70499808-c2b9-4be2-ae11-0ab4b3a1a115/mainraw · history · blame

#include <stdio.h>
#include <libmawk.h>

/*
	Purpose: demonstrate how to get the current value of an existing array index;
	Run: ./app -f test.awk
*/

void print_bar(mawk_state_t *m)
{
	mawk_cell_t c = libmawk_empty_cell;
	char buff[32];

	/* get the value of bar["wow"] into &c; the last 0 in the call means
	   the index should not be created in the array if it does not exist.
	   The array is not created if it didn't exist but -1 is returned.
	   NOTE: c must be initialized empty because it gets destroyed in
	   the call. */
	switch(libmawk_get_array_at(m, "bar", "wow", &c, 0)) {
		case -1:
			printf("No such array \"bar[]\"\n");
			break;
		case 0:
			printf("No \"wow\" in array \"bar[]\"\n");
			break;
		case 1:
			printf("app: bar = '%s'\n", libmawk_print_cell(m, &c, buff, sizeof(buff)));
			libmawk_cell_destroy(m, &c);
	}
}

int main(int argc, char **argv)
{
	mawk_state_t *m;

	/* init a context, execute BEGIN */
	m = libmawk_initialize(argc, argv);
	if (m == NULL) {
		fprintf(stderr, "libmawk_initialize failed, exiting\n");
		return 1;
	}

	/* print value of bar right after BEGIN */
	print_bar(m);

	/* feed in some data on the virtual stdin */
	libmawk_append_input(m, "This is a\nmultiline test input\nfor the artificial input buffer.\n");

	/* run the MAIN part of the script as long as there's data in the buffer of
	   the virtual stdin */
	libmawk_run_main(m);

	/* print value of bar after running the script on a few records */
	print_bar(m);


	/* run END and free the context */
	libmawk_uninitialize(m);

	return 0;
}