Codebase list libmawk / debian/1.0.0-3 src / example_apps / 15_get_scalar / app.c
debian/1.0.0-3

Tree @debian/1.0.0-3 (Download .tar.gz)

app.c @debian/1.0.0-3raw · history · blame

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

/*
	Purpose: demonstrate how to get the current value of a variable;
	         this basic example does not cover how to efficiently use
	         the value (the cell of the variable), only converts it to
	         string for printing. Please refer to examples TODO for
	         more details on cell conversions.
	Run: ./app -f test.awk
*/

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

	c = libmawk_get_var(m, "bar");

	if (c != NULL)
		printf("app: bar = '%s'\n", libmawk_print_cell(m, c, buff, sizeof(buff)));
	else
		printf("No such variable \"bar\"\n");
}

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;
}