Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Getting command line parameters outside argv passed to main




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:
http://lists.apple.com/mailman/options/darwin-dev/email@hidden

This email sent to email@hidden

References: 
 >Getting command line parameters outside argv passed to main (From: Shawn Erickson <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.