c++cwindowswinapicreateprocess

How do I convert argv to lpCommandLine parameter of CreateProcess?


Let I want to write an application, that launches another application. Like this:

# This will launch another_app.exe
my_app.exe another_app.exe 
# This will launch another_app.exe with arg1, arg and arg3 arguments
my_app.exe another_app.exe arg1 arg2 arg3

The problem here is that I'm getting char* argv[] in my main function, but I need to merge it to LPTSTR in order to pass it to CreateProcess.

There is a GetCommandLine function, but I cannot use it because I'm porting code from Linux and tied to argc/argv (otherwise, it's a very ugly hack for me).

I cannot easily merge arguments by hand, because argv[i] might contain spaces.

Basically, I want the reverse of CommandLineToArgvW. Is there a standard way to do this?


Solution

  • The definitive answer on how to quote arguments is on Daniel Colascione's blog:

    https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way

    I am reluctant to quote the code here because I don't know the license. The basic idea is:

    for each single argument:
        if it does not contain  \t\n\v\", 
            just use as is
        else
            output "
            for each character
                backslashes = 0
                if character is backslash
                    count how many successive backslashes there are
                fi
                if eow
                    output the backslashs doubled
                    break
                else if char is "
                    output the backslashs doubled
                    output \"
                else
                    output the backslashes (*not* doubled)
                    output character
                fi
            rof
            output "
        fi // needs quoting
    rof // each argument
    

    If you need to pass the command line to cmd.exe, see the article (it's different).

    I think it is crazy that the Microsoft C runtime library doesn't have a function to do this.