Look! An xargs!! (Re: recursive grep)

Bruce Barnett barnett at crdgw1.crd.ge.com
Sat Sep 9 06:57:46 AEST 1989


In article <10978 at smoke.BRL.MIL>, gwyn at smoke (Doug Gywn) writes:

>Why not simply write a genuine xargs implementation, say in C where you
>can do it right without a lot of hassle.

Hear! hear!

Who really cares if you can *ALMOST* do it in 35 lines when you can do
it *RIGHT* in 70?

Forgive this posting of the sources in this newsgroup, but maybe it will
reduce the noise level. Here is the version of xargs.c from comp.sources.whatever

/* xargs -- quickie version of System V xargs(1): read a list of
 *	arguments from stdin, apply to the command which is
 *	the argument(s) of xargs
 */

#include <stdio.h>

char *cmdname;		/* should point to argv[0] */

char command[BUFSIZ];	/* command given to xargs */
char line[BUFSIZ];	/* current input line */
char cmdbuf[BUFSIZ];	/* command + input lines */

main(argc, argv)
	int argc;
	char *argv[];
{
	char *gets();
	char *strcat(), *strcpy();

	cmdname = argv[0];

	/* skip (xargs) command name */

	argv++, argc--;

	/* construct command from arguments */

	strcpy(command, "exec");
	while (argc--) {
		(void) strcat(command, " ");
		(void) strcat(command, *argv++);
	}

	/* initialize for command execution loop */

	(void) strcpy(cmdbuf, command);

	/* here's where all the action is: read in arguments
	 * from stdin, appending to the current command buffer
	 * if next line would overflow command buffer, execute
	 * command buffer and reinitialize
	 */

	while (gets(line) != NULL) {

		/* the "+2" is for the blank and trailing null char */

		if (strlen(cmdbuf)+strlen(line)+2 > BUFSIZ) {
			docmd(cmdbuf);
			(void) strcpy(cmdbuf, command);
		}
		(void) strcat(cmdbuf, " ");
		(void) strcat(cmdbuf, line);
	}

	/* see if there is any left to do */

	if (strlen(cmdbuf) != strlen(command)) {
		docmd(cmdbuf);
	}
}

docmd(cmdbuf)
char *cmdbuf;
{
	return system(cmdbuf);
}

--
Bruce G. Barnett	<barnett at crd.ge.com>   uunet!crdgw1!barnett



More information about the Comp.unix.wizards mailing list