c++ - 如何将 system() 函数的输出重定向到变量?

标签 c++

我有这个代码:

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/

相关文章:

c++ - 如何关闭一段 Lua 代码

c++ - 使用 stringstream float 的字符串

c++ - 未知自定义结构上的结构化绑定(bind)

c++ - vector move 构造函数比复制构造函数慢

c++ - CFile Copy 方法修复文件访问被拒绝问题

c++ - 为什么 vector::insert 的重载返回 void?

c++ - 如何使用我的 if-else 语句根据输入的用户体重执行特定操作,然后将其显示到控制台?

c++ - 如何在 Visual Studio 6.0 中调试在 ASP 页面中创建的 COM 对象?

c++ - GTKMM:截屏 DrawingArea?

c++ - MFC 中 AddString 的性能缓慢