2 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
在windows下面這個(gè)的確是需要用管道來實(shí)現(xiàn)的
VC6參考代碼:
#include <windows.h>
#include <stdio.h>
BOOL ExcudeCmd(char *szOutPutBuf,char *szCmdLine)
{
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE; //輸出重定向
if (!CreatePipe(&hRead,&hWrite,&sa,0))
{
printf("創(chuàng)建匿名管道失敗");
return FALSE;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si,sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdInput=hRead;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE); //把創(chuàng)建進(jìn)程的標(biāo)準(zhǔn)錯(cuò)誤輸出重定向到管道輸入
si.hStdOutput = hWrite; //把創(chuàng)建進(jìn)程的標(biāo)準(zhǔn)輸出重定向到管道輸入
si.wShowWindow = SW_HIDE;
si.dwFlags =STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
if (!CreateProcess(NULL, szCmdLine,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi))
{
CloseHandle(hWrite);
CloseHandle(hRead);
printf("創(chuàng)建子進(jìn)程失敗");
return FALSE;
}
else
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
DWORD bytesRead;
if (!ReadFile(hRead,szOutPutBuf,1000,&bytesRead,NULL))
{
printf("讀數(shù)據(jù)失敗");
return FALSE;
}
CloseHandle(hRead);
return TRUE;
}
int main()
{
char cmdline[]="cmd.exe /c echo 回顯的信息",buf[1000];
ZeroMemory(buf,100);
ExcudeCmd(buf,cmdline);
printf(buf);//buf就是你想要的東西
}
Linux下面就不清楚了

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以試下類似的代碼,popen 函數(shù)在 vc6 中對(duì)應(yīng)的應(yīng)該是 _popen ,pclose 為 _pclose
或者百度 “c++ 獲取 system 的輸出” 您可以得到很多類似的問題的解決方案。
#include <stdio.h> #include <string> void executeCMD( const char *cmd, char *result) { char buf_ps[1024]; char ps[1024]={0}; FILE *ptr; strcpy (ps, cmd); if ((ptr=popen(ps, "r" ))!=NULL) { while ( fgets (buf_ps, 1024, ptr)!=NULL) { strcat (result, buf_ps); if ( strlen (result)>1024) break ; } pclose(ptr); ptr = NULL; } else { printf ( "popen %s error\n" , ps); } } int main() { char result[1024]; executeCMD( "find . -name \"A.txt\"" , result); printf ( "%s" , result ); return 0; } |
添加回答
舉報(bào)