Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

catching output of a called program

Status
Not open for further replies.

nickhills

Programmer
Oct 18, 2001
34
GB
Hello all,

I am trying to catch the output of a program I am calling using shellexecute() to (initially) a text file, but I am a little perplexed as to how to do it. The code executes properly and calls the ‘arp.exe’ app, but now I just need to pipe the output to the fstream…any ideas?

ShellExecute(NULL, "open","arp.exe", somearguments, NULL, SW_SHOWNORMAL)

Thanks guys,

Nick
 
If you run this from a console app you can use _popen() which is pretty simple:

#include <stdio.h>
#include <iostream>
#include <fstream>

using namespace std;

void main(void)
{
char buffer[128];
FILE *chkdsk;

if(!(chkdsk = _popen(&quot;dir c:\\*.* /on /p&quot;, &quot;rt&quot;))) return;

ofstream ofs(&quot;C:\\testpipe.txt&quot;);
while(!feof(chkdsk)) if(fgets(buffer,128,chkdsk)) ofs << buffer;

ofs << &quot;\nProcess returned &quot; << _pclose(chkdsk);
}


otherwise it's a bit more complex:

#include <windows.h>
#include <string>
#include <iostream>

using namespace std;

string ExecCmd(char* cmdline)
{
PROCESS_INFORMATION proc;
int ret;
STARTUPINFO start;
SECURITY_ATTRIBUTES sa;
HANDLE hReadPipe;
HANDLE hWritePipe;
unsigned long bytesread;
char mybuff[2048];

ZeroMemory(&sa,sizeof(sa));
sa.nLength = sizeof(sa);
sa.bInheritHandle = 1;
sa.lpSecurityDescriptor = NULL;

ret = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
if (!ret) return &quot;CreatePipe failed&quot;;

ZeroMemory(&start,sizeof(start));
start.cb = sizeof(start);
start.dwFlags = STARTF_USESTDHANDLES;
start.hStdOutput = hWritePipe;
start.hStdError = hWritePipe;

ret = CreateProcess(0, cmdline, &sa, &sa, 1, NORMAL_PRIORITY_CLASS, 0, 0, &start, &proc);
if (!ret) return &quot;CreateProcess failed&quot;;
WaitForSingleObject(proc.hProcess,INFINITE);
ret = ReadFile(hReadPipe, mybuff, 2048, &bytesread, NULL);

mybuff[bytesread] = 0;
if (!ret) return &quot;ReadFile failed&quot;;

ret = CloseHandle(proc.hProcess);
ret = CloseHandle(proc.hThread);
ret = CloseHandle(hReadPipe);
ret = CloseHandle(hWritePipe);

return mybuff;
}


int main(int argc, char* argv[])
{
cout << ExecCmd(&quot;arp.exe -a&quot;).c_str() << endl;
return 0;
}

:) Hope that this helped! ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top