11

I need to pass command line arguments from A.exe to B.exe. If A.exe with multi-args like

A.exe -a="a" -b="b"'

and I can use

BeginProcess("B.exe", **args!**)

to start B.exe. How can I get the raw command line arguments like

'-a="a" -b="b"'

0

7 Answers 7

13

If you are on Windows, you use GetCommandLine to get the raw command line.

Note that GetCommandLine also includes argv[0]. So you will have to go beyond argv[0] from the output of GetCommandLine before passing it to B.

This is some non-error checked code to do that

#include <string.h>
#include <windows.h>
#include <iostream>
#include <ctype.h>

int main(int argc, char **argv)
{
    LPTSTR cmd  = GetCommandLine();

    int l = strlen(argv[0]);

    if(cmd == strstr(cmd, argv[0]))
    {
        cmd = cmd + l;
        while(*cmd && isspace(*cmd))
            ++cmd;
    }

    std::cout<<"Command Line is : "<<cmd;

}

When I run the above program as A.exe -a="a" -b="b", I get the following output

A.exe -a="a" -b="b"
Command Line is : -a="a" -b="b"
6
  • 1
    For completeness, note that in this particular case you don't necessarily have to separate out the first part of the command line. The CreateProcess function allows you to specify the executable explicitly rather than as part of the command line. Jan 7, 2013 at 2:02
  • 2
    Don't use this code. It will fail if the executable name is enclosed in quotes (which can happen even if there are no spaces in its path). For a correct implementation, look at Wine's implementation of CommandLineToArgvW. @harry-johnston: you still need to remove the executable path in order to replace it with the program you want to run, unless you're spawning a copy of yourself.
    – benrg
    Apr 26, 2016 at 21:12
  • @benrg: no, you don't, that was my point. If you explicitly specify the executable via the lpApplicationName argument, the executable specified in the lpCommandLine argument is ignored. Apr 26, 2016 at 21:26
  • @harry-johnston: from memory, and my reading of the CreateProcess documentation, if lpApplicationName is not NULL then lpCommandLine contains only the arguments, so the old executable name will end up as argv[1] if you don't remove it.
    – benrg
    Apr 26, 2016 at 21:36
  • 1
    @benrg: no, the command line is passed to the application as-is, so you still need to specify an application name for argv[0]. (It just doesn't have to be the actual application name.) From the docs: "Because argv[0] is the module name, C programmers generally repeat the module name as the first token in the command line." I have code that relies on this behaviour, so I can confirm from personal experience that this is how it works. :-) Apr 26, 2016 at 21:47
8

Here is the one and only correct way to skip the executable name, based on Wine's implementation of CommandLineToArgvW:

char *s = lpCmdline;
if (*s == '"') {
    ++s;
    while (*s)
        if (*s++ == '"')
            break;
} else {
    while (*s && *s != ' ' && *s != '\t')
        ++s;
}
/* (optionally) skip spaces preceding the first argument */
while (*s == ' ' || *s == '\t')
    s++;

Note! Current Wine implementation, as of Feb 19 2'20 - git commit a10267172, is now moved from dlls/shell32/shell32_main.c to dlls/shcore/main.c.

2
  • Why is there not any need to handle escaped quotes? Aug 7, 2022 at 0:26
  • 1
    @JoshuaPerrett There is no escaping mechanism. There's no need for one because the executable name is a filesystem path, and Win32 paths can't contain quotation marks.
    – benrg
    Aug 7, 2022 at 23:10
2

The standard definition of main is

int main(int argc, char* argv[])

The argv variable contains the command-line arguments. The argc variable indicates how many entries in the argv array are used.

8
  • Yes, this is right. But I need to join argv to a single string.
    – miaodadao
    Jan 4, 2013 at 2:50
  • @miaodadao If you are using C++, that can be done quite easily with a for loop and std::string. If you are using C, look at the strcat() function. Jan 4, 2013 at 2:51
  • 1
    That approach tends to mangle the command line if the syntax isn't fairly simple. As a trivial example, you lose multiple spaces between arguments. Jan 7, 2013 at 1:16
  • @HarryJohnston, why would you lose multiple spaces? std::string(argv[1])+argv[2] preserves whatever spaces are in the arguments. Do you mean the new process can't reliably separate the arguments again? If so, that was exactly my criticism in the comments to PotatoSwatter's answer ... passing argv preserves individual arguments, concatenating and resplitting doesn't. Jan 7, 2013 at 14:28
  • 2
    @JonathanWakely: in Microsoft C, at least, whitespace is trimmed from argv[], so concatenating argv[1] and argv[2] loses any whitespace that was originally between argument 1 and argument 2. GetCommandLine preserves the whitespace exactly as it was originally passed. (Of course, most of the time it's OK to do argv[1] + " " + argv[2] because the new process is probably going to discard any extra whitespace anyway. But there are edge cases.) Jan 7, 2013 at 20:12
1

The raw string typed into the shell is converted by the shell into argv before your program begins running. I've never heard of an operating system or shell providing a "raw" command-line in addition to argv.

What if the user used quotes to pass a space character into your arguments? What if they used a backslash to escape a quote inside the quotes? Different shells may even have different quoting rules.

If you have a list like argv, you should try to find an API that accepts that rather than attempting to implement string processing which is only auxiliary to the actual goal. Microsoft is serious about security and they certainly provide something that doesn't require adding a security hole to your application.

I can't find documentation about any C/C++ API BeginProcess; I'm kind of assuming this is Windows but in any case you should double check your platform's reference manual for an alternative system call.

16
  • 5
    I've never heard of an operating system or shell providing a "raw" command-line in addition to argv. Win32 provides it via GetCommandLine (and presumably you have to parse it yourself ... eurgh! how primitive!) I assume BeginProcess is meant to be CreateProcess Jan 4, 2013 at 3:13
  • 1
    @JonathanWakely hehe, usually I avoid hearing more things about Windows, but it looks like I slipped up this time :D . Hmm, following the link it sounds like they provide a parser function too, and it was introduced in Windows XP so perhaps the string is sanitized already. M$ seems to introduce APIs mainly in response to clueless customers' complaints, to provide easy answers and reduce cost of their developer support. Jan 4, 2013 at 3:17
  • @JonathanWakely - It would be primitive if that were the only thing provided. However, if you are getting both (parsed argv + raw commandline, how is that primitive? It's useful if you have to do the exact thing which the OP asked about - passing the arguments through to a different program. If not for it, you would have to do the primitive thing to concatenating argv back to recreate the original full argument.
    – user93353
    Jan 4, 2013 at 3:19
  • 1
    @user93353, but then the other program (or the CreateProcess function more likely) has to re-parse the string. If you wanted to slightly modify the arguments for the new process, to add or remove something, you have to care about quoting and escaping. The execv() family of functions allow you to pass an array of arguments that are already split into separate words, which is much safer (no quoting or escaping problems possible.) It was a solved problem long before Windows existed. Jan 4, 2013 at 3:25
  • 1
    @JonathanWakely Haha, does a "problem" exist if the solution precedes it? It's nice to have a platform for people who want functions such as this to exist. Certainly it reduces the noise level in the UNIX world. Jan 4, 2013 at 3:31
1

If you're on Windows, I believe the correct solution is to call GetCommandLine() to get your full commandline, and then PathGetArgs(CommandLine) to remove arg0 (your exe path) from the beginning.

0

This is how I turn the command line back into shell args. Sometime this is nice to echo into an output file, to save "what arguments were used" along with the output. The escaping is rudimentary, and sufficient for most situations.

I started the output at the command (i=0). You can change to (i=1) if you want arguments only, etc.

//you have to free() the result!, returns null if no args
char *arg2cmd(int argc, char** argv) {
    char *buf=NULL;
    int n = 0;
    int k, i;
    for (i=0; i <argc;++i) {
        int k=strlen(argv[i]);
        buf=( char *)realloc(buf,n+k+4);
        char *p=buf+n;
        char endq=0;
        // this is a poor mans quoting, which is good enough for anything that's not rediculous
        if (strchr(argv[i], ' ')) {
            if (!strchr(argv[i], '\'')) {
                *p++='\'';
                endq='\'';
            } else {
                *p++='\"';
                endq='\"';
            }
        }
        memcpy(p, argv[i], k);
        p+=k;
        if (i < (argc-1)) *p++=' ';
        if (endq) *p++=endq;
        *p='\0';
        n = p-buf;
    }
    return buf;
}

And a simple cpp wrapper:

std::string arg2string(int argc, char **argv) {
    char *tmp=arg2cmd(argc, argv);
    std::string ret=tmp;
    free(tmp);
    return ret;
}
0

In C++/CLI there's this:

String^ cmdarg = Environment::CommandLine;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.