Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Command line interpreter/parser in UNIX

Status
Not open for further replies.

michyrec

Programmer
Feb 11, 2002
2
US
I am supposed to write a shell using C, and someone told me that there is a good command to help with parsing the command line, but I cannot find it. I have never programmed in C before and I was wondering if anyone had some pointers (hehe).

Michele
 
There are easy ways to interpret command line args when they're passed as part of kicking off your executable:

Like so:

#include <stdio.h>

void main( int argc, char *argv[] )
{
int count;

/* Display each command-line argument. */
printf( &quot;\nCommand-line arguments:\n&quot; );
for( count = 0; count < argc; count++ )
printf( &quot; argv[%d] %s\n&quot;, count, argv[count] );

return;
}

Let me know this isn't what you meant.
 
I think that they want me to run the program, and then type things after the program is running already and get the arguments. That way, I can't just use the argv[] options.
 
Try the following:

main()
{
char ch = 0;
char cBuff[255];
char cOptList[100];
char * pcOption = 0;
int iCount = 0;

for( iCount = 0; (iCount < 80) && ((ch = getchar()) != EOF)
&& (ch != '\n'); iCount++ )
cBuff[iCount] = ( char )ch;

iCount = 0;
pcOption = strpbrk( cBuff, &quot;-&quot; );
while( pcOption != NULL )
{
cOptList[iCount] = *(pcOption + 1);
pcOption = strpbrk( cBuff, &quot;-&quot; );
iCount++;
}
// Process list of options here
}

This only works for single char options (if it works at all), but it can be adapted.

 
Michyrec, I bet the command you need is 'getopt'. This is a command that can process arguments that consist of flag arguments and value arguments. Flag arguments are a dash immediately followed by a single character, ie '-a'. Value arguments are a flag argument followed by an optional space character followed by some value argument. Using an example may help.
Code:
ping -a -c 5

In this command, the '-a' is a flag and the '-c 5' is a value.

Check out the 'man' page for this command.

GAFling
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top