Codebase list libmawk / fresh-releases/upstream src / example_apps / 12_input / app.c
fresh-releases/upstream

Tree @fresh-releases/upstream (Download .tar.gz)

app.c @fresh-releases/upstreamraw · history · blame

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

/*
(this test is broken yet, waiting for vio to be finished)
	Purpose: demonstrate how virtual stdin works
	Run: ./app -f test.awk
*/

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

	/* run the MAIN part of the script; assume a record is a line
	   (with standard FS in awk this is true). The MAIN part of
	   the script consists of _all_ rules except for BEGINs and ENDs. */

	/* The input buffer of the script is empty at start. Attempting to run
	   MAIN on an empty buffer will return immediately, without any awk
	   code being executed */
	printf("app: test point 1\n");
	libmawk_run_main(m);

	/* Load a full record and invoke MAIN; this will run rules once, for this
	   line: */
	printf("app: test point 2\n");
	libmawk_append_input(m, "First line.\n");
	libmawk_run_main(m);

	/* Load a multiple records and invoke MAIN; this will run the rules
	   for all full (terminated) records:
	*/
	printf("app: test point 3\n");
	libmawk_append_input(m, "Second line.\nThird line.\nFourth ");
	libmawk_run_main(m);

	/* At this point we have a partial record ("Fourth ") left in the
	   buffer. Running MAIN without terminating this record will have
	   the same effect as running MAIN on an empty buffer:
	*/
	printf("app: test point 4\n");
	libmawk_run_main(m);

	/* Terminate the incomplete record and run: will invoke rules on the
	   now-complete record */
	printf("app: test point 5\n");
	libmawk_append_input(m, "line.\n");
	libmawk_run_main(m);


	/* the number of append calls does not matter: */
	printf("app: test point 6\n");
	libmawk_append_input(m, "5th line.\n");
	libmawk_append_input(m, "6th line.\n7th ");
	libmawk_append_input(m, "line.\n");
	libmawk_run_main(m);

	/* if there is a partial record at the end of the input stream, that
	   is read and processed as a full record */
	printf("app: test point 7\n");
	libmawk_append_input(m, "partial 8th 'line'\n");
	libmawk_close_input(m);
	libmawk_run_main(m);

	/* free the context - this won't run END because END had to run already
	   for eof-on-stdin */
	printf("app: test point 8\n");
	libmawk_uninitialize(m);

	return 0;
}