Search code examples
c++system

system call in c++ opens a new terminal . windows


I am trying out system command in c++ .

std::string cmd = " DIR > d:\a.txt" ; 
int isystemOut2 = system (cmd.c_str());

When I run it , I see that d:\a.txt has the right output but I see a command prompt open and close immediately . Is there a way to stop that opening of a new command prompt .


Solution

  • You could use a windows API function. For example CreateProcess.

    STARTUPINFOW si;
    PROCESS_INFORMATION pi;
    
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    
    if (CreateProcessW(cmd, arg, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
    {
        WaitForSingleObject(pi.hProcess, INFINITE);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }