Using filters within C code - example
Charles Weir
cweir at richsun.reuter.com
Fri Jun 15 13:12:01 AEST 1990
I attach a piece of code which I have found extremely useful. It is a
function which executes an operating system command and returns the text
output from it.
This posting was prompted by the message from halam2 at umn-d-ub.D.UMN.EDU
(Haseen I. Alam) asking talking about a call like
system ("wc -c filename") ;
This does what he wanted (although, as people have pointed out, there are more
efficient ways to do it).
I find it invaluable for testing applications, since it allows me to use
standard tools from within C code.
Now for my question...
Can you advise me how portable this code is?
------------ Function follows -------------------
#include <stdio.h>
#include <errno.h>
#define MAX_RESULT 1000
/*
*******************************************************************************
* NAME: CallSystem
*
* DESCRIPTION: Routine to pipe a string through a System filter to
* generate another string.
*
* USAGE: Input strings containing "'" chars will cause an error
*
* PARAMETERS: Command: String representing the System command (may
* include shell metachars)
* InputString: The standard input to the command.
* May not contain the backquote charactor.
*
* GLOBALS: None
*
* RETURNS: Pointer to static buffer containing result of System command.
* NULL if the call fails
* The output is truncated to fit (size MAX_RESULT).
* The contents are valid until the next call to
* CallSystem.
*
* ERRORS: Returns NULL, with errno set, if the input strings are too
* big, or if the input string contains a backquote charactor.
* Also if the System command exits with a non-zero exit code.
*
******************************************************************************/
char * CallSystem( Command, InputString )
char * Command;
char * InputString;
{
int i;
static char ResultBuffer[ MAX_RESULT ];
static char CommandString[ MAX_RESULT ];
FILE * PipeFromChildToUs;
int iErr; /* Exit status of the command */
if (InputString == (char*)NULL)
InputString = "";
if (strlen( Command ) + strlen( InputString ) >
sizeof( CommandString ) - 20 ||
strchr( InputString, '\'' ) != (char * )NULL )
{
errno = EINVAL;
return (char*)NULL;
}
sprintf( CommandString, "echo '%s' | %s", InputString, Command );
PipeFromChildToUs = popen( CommandString, "r" );
if (PipeFromChildToUs == (FILE*)NULL)
Error_Program( "Cannot open pipe" );
i = fread( ResultBuffer, 1, MAX_RESULT - 1, PipeFromChildToUs );
ResultBuffer[i] = '\0';
iErr = pclose( PipeFromChildToUs ) ;
if (iErr != 0)
{
errno = iErr;
return (char*)NULL;
}
return (ResultBuffer);
}
---------------------- End function ------------------------
--
Charles Weir, Rich Inc, 1400 Kensington, Oak Brook, IL 60521
Email: cweir at richsun.uucp uunet!richsun!cweir
Phone: +1 708 574 7424 X2766
More information about the Comp.lang.c
mailing list