How do I redirect the output of the system () function to a variable?
The quick, ugly and dirty way is to redirect the output to a file and then read that file.
system("echo %username% > someFile.txt");
A more complicated way is to use the API CreateProcess
with the following command line:cmd.exe /c echo %username%
This API allows you to specify custom standard input and standard output. You can create a pipe for standard output like this:
HANDLE g_hChildStd_OUT_Wr = NULL;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process STDOUT.
//
if ( !CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) ) return -1;
And then use that pipe in the CreateProcess API. Something like that:
TCHAR szCmdline[]=TEXT("cmd.exe /c echo %username%");
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
// Set up members of the PROCESS_INFORMATION structure.
//
memset( &piProcInfo, 0, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
//
memset( &siStartInfo, 0, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// Create the child process.
//
bSuccess = CreateProcess(NULL,
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent environment
NULL, // use parent current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
And then it reads something like this from the pipe:
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
for (;;)
{
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess || dwRead == 0 ) break;
}
The process will run asynchronously, so you need to know when the process has finished and clean up properly. So there is a bunch of details here to find out here to make this work.
A complete example can be found here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
source to share
If the goal is only to obtain a username, do you consider getenv
; getenv( "username" )
will return it directly.
Otherwise, if you have more of what you want to do and want the results in a file ... The string passed to system
is passed to the shell, so anything you can do on the command line in cmd.exe
will work in system
: redirect files, connection to another process, etc.
source to share