Search code examples
c++windowsvisual-c++shellexecutewchar-t

Initialise wchar_t with dynamic length


first I have to mention, that I am an absolute C++ beginner, so don't throw any stones. I want to kill an external program with the help of ShellExecute and delete a log file as simple as possible. On linux I can use system (and it works perfect), but on windows an annoying dosbox pops up. With the help of a lot of google I managed to write this code:

wchar_t command[1024] = L"b";
swprintf_s(command, _countof(command), L"/C TASKKILL /IM ExternalProgram.exe /F & del \"%S\"", logFilePath);
ShellExecute( NULL, L"open", L"cmd.exe", command, NULL, SW_HIDE );

logFilePath is char. This code works as long as I use a short path e. g. c:\MyProgram\logfile.txt. If the path to log file is longer e. g. c:\program files\My Program\anything\more\xxx\...\logfile.txt the program crashes. I understand, that 1024 is the max length of the variable, but how do I tell C that I don't know the length?

I tried to get around it by using strlen(logFilePath)+50 but this only gave me compile errors. What is the correct way?


Solution

  • There are a lot of ways to do this. Instead of giving you 15 options I'm just going to tell you what I would do:

    #include <sstream>
    
    std::wstringstream strStream;
    strStream << L"/C TASKKILL /IM ExternalProgram.exe /F & del \"" << logFilePath << L"\"";
    std::wstring command = strStream.str();
    ShellExecute( NULL, L"open", L"cmd.exe", command.c_str(), NULL, SW_HIDE );
    

    This way is a little more C++ish and less Cish.

    Oh, and to address why your attempt didn't work: You can only have dynamically sized arrays (arrays whose size is determined in runtime) if they are allocated in the heap. You would have to do...

    wchar_t* command = new wchar_t[strlen(logFilePath)+50];
    //...
    delete [] command;