I'm trying to get the CreateProcessA function to work, but it continues giving me trouble and more trouble.

Here's the code:

#include <iostream>
#include <string>
#include <windows.h> // CreateFile(), CreateProcess(), OpenFile(), etc. and
                     // STARTUPINFO, PROCESS_INFORMATION
#include <ctime>     // srand(), time(NULL)
#include <cstdlib>   // rand()

using namespace std;

string execute(const string & szCmdLine, bool fRedirectOutput = false)
{
    string ret;

    HANDLE hProcess;
    HANDLE hFile;
    STARTUPINFO si; memset(&si, 0, sizeof(STARTUPINFO));
    PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(PROCESS_INFORMATION));

    srand(time(NULL));
    char s[100];
    sprintf(s, "%u", rand());
    string sTempFile = string(getenv("TEMP"))+"\\tmp"+string(s)+".txt";
    if (fRedirectOutput)
    {
        si.cb = sizeof(STARTUPINFO);
        si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
        si.wShowWindow = SW_HIDE;

        hFile = CreateFileA(sTempFile.c_str(),
        GENERIC_READ | GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS,
            NULL, NULL);
        if (hFile)
        {
            si.hStdOutput = hFile;
        }
    }

    BOOL bResult = CreateProcessA(NULL, (LPSTR)szCmdLine.c_str(), NULL,
        NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
    if (bResult)
    {
        WaitForSingleObject(pi.hProcess, INFINITE);
    }

    if ((bool)hFile && fRedirectOutput)
    {
        unsigned long numOfBytes;
        char* buf;
        numOfBytes = GetFileSize(hFile, NULL);
        buf = new char[numOfBytes];
        buf[numOfBytes] = 0;

        OFSTRUCT of; memset(&of, 0, sizeof(OFSTRUCT));
        unsigned long bytesRead;
        SetFilePointer(hFile, 0, 0, FILE_BEGIN);
        ReadFile(hFile, buf, numOfBytes, &bytesRead, NULL);
        CloseHandle(hFile);

        ret = string(buf);
        DeleteFileA(sTempFile.c_str());
    }

    return ret;
}

int main(void)
{
    execute("grep 'include.*boost' \"C:\\complex.cpp\" |wc -l");
    cin.get();

    return 0;
}

And here's the output:

grep: |wc: No such file or directory

But when I type grep 'include.*boost' "C:\complex.cpp" |wc -l directly into command prompt, it shows the output that I should be receiving with CreateProcessA:

0

Can anyone help explain this problem?

Haha, I just solved my own problem! All I needed to do was append "cmd.exe /C " before the command line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.