Re: Getting command line parameters outside argv passed to main
Re: Getting command line parameters outside argv passed to main
- Subject: Re: Getting command line parameters outside argv passed to main
- From: Steve Checkoway <email@hidden>
- Date: Mon, 19 Dec 2005 12:38:09 -0800
On Dec 19, 2005, at 12:15 PM, Shawn Erickson wrote:
If no built-in feature exists I will simply grab the arguments while
in main and stash what I need in a global var for later use or
accessible via some internal api.
That's what I always do.
I suppose it might be possible to walk backward from environ to get
the command line parameters:
$ cat args.c
#include <stdio.h>
extern char **environ;
static void print_args()
{
int argc = 1;
char **argv = environ-3;
while( (int)*argv != argc )
{
++argc;
--argv;
}
printf( "%s", *(++argv) );
while( *(++argv) )
printf( " %s", *argv );
puts( "" );
}
int main( int argc, char **argv )
{
print_args();
return 0;
}
$ gcc -Wall args.c
$ ./a.out This is a test.
./a.out This is a test.
That said, it's probably easier and safer to just store them. The
above code assume that argv[0] is the path of the program which
doesn't have to be the case. It also assumes that sizeof( int ) ==
sizeof( char * ), also not a reasonable assumption to make for
portable code. Lastly, it assumes that the arguments to main are laid
out in memory in the order:
argc argv[0] argv[1]...argv[argc-1] NULL environ[0]...environ[n] NULL
That might be a reasonable assumption to make.
- Steve
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden