Hide console in C system() function, Win

Viewed 44509

I am coding a C program in Dev-C++, and I need to use a couple of Windows (CMD) commands. It is easy, but when the command in the system() function is executed, the program runs the console in the execution.

An example:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

    int main()
    {
      system("if not exist c:\my_docs\doc.txt (xcopy /Y doc.txt c:\my_docs\)"); // Cmd command
      system("pause");
      return 0;
    }

Exists other function, or a modification that do not shows the console?

Thanks you! Best regards.

5 Answers
int win_system(const char *command)
{
    // Windows has a system() function which works, but it opens a command prompt window.
    
    char            *tmp_command, *cmd_exe_path;
    int         ret_val;
    size_t          len;
    PROCESS_INFORMATION process_info = {0};
    STARTUPINFOA        startup_info = {0};

    
    len = strlen(command);
    tmp_command = malloc(len + 4);
    tmp_command[0] = 0x2F; // '/'
    tmp_command[1] = 0x63; // 'c'
    tmp_command[2] = 0x20; // <space>;
    memcpy(tmp_command + 3, command, len + 1);
    
    startup_info.cb = sizeof(STARTUPINFOA);
    cmd_exe_path = getenv("COMSPEC");
    _flushall();  // required for Windows system() calls, probably a good idea here too
    
    if (CreateProcessA(cmd_exe_path, tmp_command, NULL, NULL, 0, CREATE_NO_WINDOW, NULL, NULL, &startup_info, &process_info)) {
        WaitForSingleObject(process_info.hProcess, INFINITE);
        GetExitCodeProcess(process_info.hProcess, &ret_val);
        CloseHandle(process_info.hProcess);
        CloseHandle(process_info.hThread);
    }
    
    free((void *) tmp_command);
    
    return(ret_val);
}
Related