views:

1072

answers:

2

Hello.

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.

+2  A: 

You can do it with CreateProcess.

STARTUPINFOW si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

if (CreateProcessW(command, arg, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
}
FigBug
+1 Thanks you, I will test it. It is not exactly what I was looking for, but is a good answer.
a0rtega
+3  A: 

As FigBug stated, CreateProcess() is the way to go, but I don't think that CreateProcess() can execute a shell if statement. You may need to pass it something like this as a command:

"cmd.exe /c \"if not exist c:\my_docs\doc.txt (xcopy /Y doc.txt c:\my_docs\)\""

But a better solution might be to use CreateFile() to test if a file exists and CopyFile() to copy it.

Ferruccio
+1 Finally I did it, is the best solution in this case.
a0rtega