Hey guys, quick question:
I have been experementing with the _popen() function to get the stdout from programs. I'm trying to wrap it in a function for quick reuse, but the prog crashes every time!
Here is the function (as well as the quick test main() function):
// crt_popen.c
/* This program uses _popen and _pclose to receive a
* stream of text from a system process.
*/
#include "StdAfx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string>
#include <iostream>
char getStdOut(char*);
int main( void )
{
std::cout << getStdOut("ls");
_getch();
}
char getStdOut(char *cmd)
{
char psBuffer[128];
char ps[1024];
FILE *pPipe;
if( (pPipe = _popen(cmd, "rt" )) == NULL )
exit( 1 );
/* Read pipe until end of file, or an error occurs. */
while(fgets(psBuffer, 128, pPipe))
{
strcat(ps,psBuffer);
memset(psBuffer, 0, sizeof(psBuffer) );
}
/* Close pipe and print return value of pPipe. */
if (!feof( pPipe))
{
printf( "Error: Failed to read the pipe to the end.\n");
}
return *ps;
}
In VS2010, it keeps running into an Access Violation.
Unhandled exception at 0x77df158e in PipesTest.exe: 0xC0000005: Access violation.
Thanks guys!