Search code examples
c++shellexecuteshellexecuteex

Insert (dynamic) command string in ShellExecute function in C++


Using C++ (on Windows 10), I'm trying to execute a command in cmd.exe that execute a python file that takes in another file (in csv format). What I would like to do is the same thing as if I were typing on the command line something like this:

python3 .\plotCSV.py .\filetoplot.csv

Or in better mode:

python3 C:\...\Documents\plotCSV.py C:\...\Documents\filetoplot.csv

For this I'm using ShellExecute like this:

ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", "/c \"python3 C:\...\Documents\plotCSV.py C:\...\Documents\filetoplot.csv\"", NULL, SW_SHOWDEFAULT);

And for the csv file selected (filetoplot.csv for example) this works. Except that, for what I need, the name of the csv file is generate and changes every time in my C++ program and is saved in a variable file_name.c_str(). So, if I use this in ShellExecute I have:

ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", "/c \"python3 C:\...\Documents\plotCSV.py C:\...\Documents\file_name.c_str()\"", NULL, SW_SHOWDEFAULT);

But unfortunately (obviously) it doesn't work because there really isn't a csv file renamed "file_name.c_str()".

I found also the function ShellExecuteEx and wanting to repeat the same procedure I think the function should be used like this:

SHELLEXECUTEINFO info = {0};

        info.cbSize = sizeof(SHELLEXECUTEINFO);
        info.fMask = SEE_MASK_NOCLOSEPROCESS;
        info.hwnd = NULL;
        info.lpVerb = NULL;
        info.lpFile = "cmd.exe"; 
        info.lpParameters = ("python3 C:\...\Documents\plotCSV.py C:\...\Documents\file_name.c_str()");
        info.lpDirectory = NULL;
        info.nShow = SW_SHOW;
        info.hInstApp = NULL;

        ShellExecuteEx(&info);

But even here it doesn't work (I probably misinterpret how the function works).

Hoping I have explained myself well, I kindly ask for your advice on how to proceed in this regard.

Thank you very much


Solution

  • You are trying to write code inside a string literal.
    That is not possible in C++!

    You need to first create your dynamic parameter string, then pass it to a function.
    std::string has an overloaded + operator that supports string literals (const char *).

    std::string param1 = "/c \"python3 C:\\...\\Documents\\plotCSV.py C:\\...\\Documents\\" + file_name + '\"';
    
    ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", param1.c_str(), NULL, SW_SHOWDEFAULT);