我有这个代码:
system("echo %username%");
我想将其结果重定向到一个变量,比如 uname
。
我该怎么做?
我知道 WinAPI,但我想这样做。
最佳答案
快速、丑陋和肮脏的方法是将输出重定向到一个文件,然后读取该文件。
system("echo %username% > someFile.txt");
更详细的方法是通过以下命令行使用 CreateProcess
API:cmd.exe/c echo %username%
该 API 允许您指定自定义标准输入和标准输出。您可以像这样为标准输出创建管道:
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's STDOUT.
//
if ( !CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) ) return -1;
然后在 CreateProcess API 中使用此管道。像这样:
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's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
然后用这样的方式从管道中读取:
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;
}
该进程将异步运行,因此您需要知道该进程何时终止并进行适当的清理。因此,为了完成这项工作,这里有很多细节需要学习。
一个完整的例子可以在这里找到: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
关于c++ - 如何将 system() 函数的输出重定向到变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26324150/