How do I redirect the output of the system () function to a variable?

I have this code:

system("echo %username%");


I want to redirect my result to a variable, eg uname


How can i do this?

I am aware of WinAPI, but I want to do it this way.


source to share

2 answers

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;


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%");

// 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; 
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:



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.



All Articles