delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/05/08/19:17:44

From: mert0407 AT sable DOT ox DOT ac DOT uk (George Foot)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Help needed with command line params.
Date: 8 May 1997 03:33:04 GMT
Organization: Oxford University, England
Lines: 50
Message-ID: <5krhhg$gk3@news.ox.ac.uk>
References: <336E468C DOT 35 AT avanti DOT orient DOT uw DOT edu DOT pl>
NNTP-Posting-Host: sable.ox.ac.uk
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Piotr Sieklucki (pas AT avanti DOT orient DOT uw DOT edu DOT pl) wrote:
: Hello fellow DJGPPers,

: I would like to ask for some advice. How do you read the command-line 
: parameters given to a program at runtime, and copy them to strings?
: Basically, I want to get the 2nd and 4th (given that the 1st is the
: full pathname to the program) parameters into strings <2nd> and <4th>.
: I realise that this is bloody simple, but I just seem to be bloody
: stupid. Anyone out there who can give me a helping hand, plz? TIA.

The following example should help:

#include <stdio.h> /* for printf */

int main(int argc,char **argv)
{
 int i; 
 printf("You passed %d arguments.\n",argc-1);
 printf("\tProgram name:\t%s\n",argv[0]);
 for (i=1;i<argc;i++)
  printf("\tArgument %d:\t%s\n",i,argv[i]);
 return 0;
}

argv is an array of strings, effectively, with as many elements as there
were `words' on the command line. Note that this includes the program
name. argc is the dimension of argv (number of elements in it), so the
number of parameters passed is (argc-1).

argv[0] is always the program's name. I'm not sure if it's a standard
thing to do, but under DJGPP this is expanded to what Microsoft call a
Well Formed Path (WFP), with the drive, full path, and filename of the
executed program. I'm not sure whether it's DJGPP or DOS which is doing
this though. 

argv[1] is a null-terminated string, containing the first parameter. If
you expect a number for a parameter, you'll have to atoi() it. argv[2] is
the second parameter, etc up to argv[argc-1] which is the last parameter.

You should check the value of argc before referring to anything higher
than argv[0], though, in case the user didn't pass that number of
parameters.

Note that crt0.h declares __crt0_argc and __crt0_argv, which are the
parameters passed to main anyway, so if you don't want to receive them as
paramters to main you can read these global variables.

-- 
George Foot <mert0407 AT sable DOT ox DOT ac DOT uk>
Merton College, Oxford

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019