2 回答

TA贡献2016条经验 获得超9个赞
在windows下面这个的确是需要用管道来实现的
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("创建匿名管道失败");
return FALSE;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si,sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.hStdInput=hRead;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE); //把创建进程的标准错误输出重定向到管道输入
si.hStdOutput = hWrite; //把创建进程的标准输出重定向到管道输入
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("创建子进程失败");
return FALSE;
}
else
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
DWORD bytesRead;
if (!ReadFile(hRead,szOutPutBuf,1000,&bytesRead,NULL))
{
printf("读数据失败");
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贡献1872条经验 获得超4个赞
您可以试下类似的代码,popen 函数在 vc6 中对应的应该是 _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; } |
添加回答
举报