У меня здесь серьезная проблема. Мне нужно выполнить командную строку CMD через C ++ без отображения окна консоли. Поэтому я не могу использовать system(cmd) , так как окно будет отображаться.
Я пробовал winExec(cmd, SW_HIDE) , но это тоже не работает. CreateProcess — еще один, который я пробовал. Однако это для запущенных программ или командных файлов.
Я попытался ShellExecute :
ShellExecute( NULL, «open», «cmd.exe», «ipconfig > myfile.txt», «c:projectsb», SW_SHOWNORMAL );
Может ли кто-нибудь увидеть что-то не так с приведенным выше кодом? Я использовал SW_SHOWNORMAL , пока не убедился, что это работает.
Мне действительно нужна помощь с этим. Ничего не выяснилось, и я уже давно пытаюсь. Любой совет, который мог бы дать кто-либо, был бы отличным 🙂
JP29 19 Июл 2012 в 19:51
Вы проверили код возврата?
19 Июл 2012 в 19:58
Я знаю, что у вас есть ответ, но обычно лучше сказать, почему это не работает.
20 Июл 2012 в 12:18
Команды в cmd для новичков
Почему бы не вызвать функции WMI_ и не записать результаты в файл. Нет окна и только данные, которые вам нужны.
graham.reeds
11 Мар 2016 в 11:35
6 ответов
Лучший ответ
Перенаправление вывода на ваш собственный канал — более аккуратное решение, потому что оно позволяет избежать создания выходного файла, но это отлично работает:
ShellExecute(0, «open», «cmd.exe», «/C ipconfig > out.txt», 0, SW_HIDE);
Вы не видите окно cmd, и вывод перенаправляется, как ожидалось.
Ваш код, вероятно, дает сбой (не считая /C ), потому что вы указываете путь как «c:projectsb» , а не «c:\projects\b» .
arx 19 Июл 2012 в 21:33
Вот моя реализация функции DosExec, которая позволяет (незаметно) выполнять любую команду DOS и получать сгенерированный вывод в виде строки Unicode.
// Convert an OEM string (8-bit) to a UTF-16 string (16-bit) #define OEMtoUNICODE(str) CHARtoWCHAR(str, CP_OEMCP) /* Convert a single/multi-byte string to a UTF-16 string (16-bit). We take advantage of the MultiByteToWideChar function that allows to specify the charset of the input string. */ LPWSTR CHARtoWCHAR(LPSTR str, UINT codePage) < size_t len = strlen(str) + 1; int size_needed = MultiByteToWideChar(codePage, 0, str, len, NULL, 0); LPWSTR wstr = (LPWSTR) LocalAlloc(LPTR, sizeof(WCHAR) * size_needed); MultiByteToWideChar(codePage, 0, str, len, wstr, size_needed); return wstr; >/* Execute a DOS command.
If the function succeeds, the return value is a non-NULL pointer to the output of the invoked command. Command will produce a 8-bit characters stream using OEM code-page. As charset depends on OS config (ex: CP437 [OEM-US/latin-US], CP850 [OEM 850/latin-1]), before being returned, output is converted to a wide-char string with function OEMtoUNICODE. Resulting buffer is allocated with LocalAlloc. It is the caller’s responsibility to free the memory used by the argument list when it is no longer needed.
To free the memory, use a single call to LocalFree function. */ LPWSTR DosExec(LPWSTR command) < // Allocate 1Mo to store the output (final buffer will be sized to actual output) // If output exceeds that size, it will be truncated const SIZE_T RESULT_SIZE = sizeof(char)*1024*1024; char* output = (char*) LocalAlloc(LPTR, RESULT_SIZE); HANDLE readPipe, writePipe; SECURITY_ATTRIBUTES security; STARTUPINFOA start; PROCESS_INFORMATION processInfo; security.nLength = sizeof(SECURITY_ATTRIBUTES); security.bInheritHandle = true; security.lpSecurityDescriptor = NULL; if ( CreatePipe( writePipe, // address of variable for write handle GetStartupInfoA( start.hStdOutput = writePipe; start.hStdError = writePipe; start.hStdInput = readPipe; start.dwFlags = STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW; start.wShowWindow = SW_HIDE; // We have to start the DOS app the same way cmd.exe does (using the current Win32 ANSI code-page). // So, we use the «ANSI» version of createProcess, to be able to pass a LPSTR (single/multi-byte character string) // instead of a LPWSTR (wide-character string) and we use the UNICODEtoANSI function to convert the given command if (CreateProcessA(NULL, // pointer to name of executable module UNICODEtoANSI(command), // pointer to command line string security, // pointer to thread security attributes TRUE, // handle inheritance flag NORMAL_PRIORITY_CLASS, // creation flags NULL, // pointer to new environment block NULL, // pointer to current directory name processInfo // pointer to PROCESS_INFORMATION ))< // wait for the child process to start for(UINT state = WAIT_TIMEOUT; state == WAIT_TIMEOUT; state = WaitForSingleObject(processInfo.hProcess, 100) ); DWORD bytesRead = 0, count = 0; const int BUFF_SIZE = 1024; char* buffer = (char*) malloc(sizeof(char)*BUFF_SIZE+1); strcpy(output, «»); do < DWORD dwAvail = 0; if (!PeekNamedPipe(readPipe, NULL, 0, NULL, // error, the child process might have ended break; >if (!dwAvail) < // no data available in the pipe break; >ReadFile(readPipe, buffer, BUFF_SIZE, buffer[bytesRead] = ‘