Search code examples
cstringwindowsunicodeunicode-string

See if WCHAR* is substring of WCHAR in C


I am using the Windows function CreateToolhelp32snapshot to enumerate running processes on my machine. The pe32.szeFileName field it returns is a WCHAR, and this is the executable's name.

I want to compare each executable name to a long array of executables I produce, like so:

WCHAR* processNames[numProcesses] = { "word", "excel", "outlook, ...}

Unfortunately, I don't know how to check if any element of this processNames array is a substring of the WCHAR returned from pe32.szeFilename.

I know wcsstr would work if I was dealing with two const wchar_t * strings. How can I compare the WCHARreturned by pe32.szeFilename with each element of an array of strings? Specifically, I want to see if any string in the array (any kind of format is fine) is a substring of the WCHAR.

EDIT: My current loop:

do {

    wprintf(L"Process name: %s\n", pe32.szExeFile);
    for (int i = 0; i < numProcesses; ++i) {
        if (wcsstr(pe32.szExeFile, processNames[i])) {
            // Found it
            wprintf("%s", pe32.szExeFile);

        }
    }

} while (Process32Next(hProcessSnap, &pe32));

Solution

  • The question tagged with unicode, so I suppose, you should try to change all literals' declaration to L"characters", e.g.:

    WCHAR* processNames[numProcesses] = { L"word", L"excel", L"outlook", ...}
    

    then check that appropriate unicode functions are used, e.g. UNICODE is defined or function names with W used:

    Process32FirstW(hProcessSnap, &pe32);
    . . . 
    Process32NextW(hProcessSnap, &pe32);
    

    and finally (start from that one, perhaps this allows you to see the result of condition of if), use L"%s" for wprintf:

    wprintf(L"%s", pe32.szExeFile);
    

    UPDATE:

    Just to check behavior of wprintf I wrote a small piece of code (Visual Studio 2013 was used), so result of

    #include <tchar.h>
    #include <windows.h>
    
    int main(void)
    {
        WCHAR* procName = L"excel";
    
        WCHAR* processNames[3] = { L"word", L"excel", L"outlook" };
    
        wprintf(L"Process name: %s\n", procName);
        for (int i = 0; i < 3; ++i) {
           if (wcsstr(procName, processNames[i])) {
               wprintf("%s", procName);
           }
        }
        return 0;
    }
    

    is

    Process name: excel

    (i.e. looks like if has false condition),

    but code (only one L added for wprintf inside loop)

    #include <tchar.h>
    #include <windows.h>
    
    int main(void)
    {
        WCHAR* procName = L"excel";
    
        WCHAR* processNames[3] = { L"word", L"excel", L"outlook" };
    
        wprintf(L"Process name: %s\n", procName);
        for (int i = 0; i < 3; ++i) {
           if (wcsstr(procName, processNames[i])) {
               wprintf(L"%s", procName);
           }
        }
        return 0;
    }
    

    shows

    Process name: excel

    excel