You need to decide where the storage for the two filenames is allocated, and how you will know how much storage is provided.
static void find_filename(const char *str, char *name)
{
char c;
while ((c = *str++) != '\0' && isspace((unsigned char)c))
;
if (c != '\0')
{
*name++ = c;
while ((c = *str++) != '\0' && !isspace((unsigned char)c))
*name++ = c;
}
}
int find_io_redirection(const char *str, char *in, char *out)
{
const char *lt = strchr(str, '<');
const char *gt = strchr(str, '>');
if (lt != 0)
find_filename(lt+1, in);
if (gt != 0)
find_filename(gt+1, out);
return(lt != 0 && gt != 0);
}
This code simply assumes that you provide big enough strings for in
and out
. If you want to be safer, then you tell the function(s) how big each target string is. You can compress that code. You might decide you want to return the number of redirections. You might decide you should know about double output redirections, or double input redirections. You might decide you should return a bit mask indicating which redirections were present. With a considerably more complex interface, you might be able to indicate which parts of the input line represented the I/O redirection; this would help in the calling function to decide which parts of the line should now be ignored.
You'd use the code above like this:
char buffer[MAXCMDLEN];
char in[MAXFILENAMELEN];
char out[MAXFILENAMELEN];
if (fgets(buffer, sizeof(buffer), stdin) != 0)
{
if (find_io_redirection(buffer, in, out))
...process buffer know that I/O redirection is present...
else
...witter about missing I/O redirection...
}