C++代码中调用DOS执行命令行代码(可以包含参数),并保存DOS命令行执行结果。
int getResultOfDOS(string command) {
char psBuffer[1024];
FILE *pPipe;
if ((pPipe = _popen(command.c_str(), "rt")) == NULL)
{
exit(1);
}
/* Read pipe until end of file, or an error occurs. */
int cnt = 0; // my own need
string res; // my own need
while (fgets(psBuffer, 1024, pPipe))
{
cnt++;
if (2 == cnt)
{
res = psBuffer;
}
}
/* Get what i need */
int startIdx = res.find_first_of('"');
res = res.substr(startIdx + 1, 1);
/* Close pipe and print return value of pPipe. */
if (feof(pPipe))
{
//printf("\nProcess returned %d\n", _pclose(pPipe));
//return std::stoi(res); // C++11
return atoi(res.c_str());
}
else
{
printf("Error: Failed to read the pipe to the end. \n");
return 0;
}
}