如何将批处理文件的输出读取到C 中的字符串中

How do I read the output of a batch file into a string in C++

本文关键字:字符串 读取 输出 批处理文件      更新时间:2023-10-16

我正在尝试制作一个将创建批处理文件的小程序,在其中做点什么,然后从中返回字符串,然后删除批处理。

我想将批处理文件的输出存储在变量line中。

我尝试使用getline(),但我认为它仅适用于.txt文件。我可能错了。

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
    ofstream batch;
    string line;
    batch.open("temp.bat", ios::out);
    batch <<"@echo OFFnwmic os get caption /valuenwmic path win32_videocontroller get description /valuenpausenexit";
    batch.close();
    system("temp.bat");
    remove("temp.bat");
};

在我的代码中,我只是在批处理文件中使用system。我想使用cout<<line

我希望字符串称为line等于批处理文件的输出。

使用System((:

时,您需要重定向输出
#include <cstdio>   // std::remove(const char*)
#include <cstdlib>  // std::system(const char*)
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
  std::string foo_bat = "foo.bat";
  std::string foo_out = "foo.out";
  // Write the batch file
  {
    std::ofstream f( foo_bat );
    f << R"z(
      @echo off
      wmic os get caption /value
      wmic path win32_videocontroller get description /value
    )z";
  }
  // Execute the batch file, redirecting output using the current (narrow) code page
  if (!!std::system( (foo_bat + " | find /v "" > " + foo_out + " 2> NUL").c_str() ))
  {
    // (Clean up and complain)
    std::remove( foo_bat.c_str() );
    std::remove( foo_out.c_str() );
    std::cout << "fooey!n";
    return 1;
  }
  // Read the redirected output file
  std::unordered_map <std::string, std::string> env;
  {
    std::ifstream f( foo_out );
    std::string s;
    while (getline( f >> std::ws, s ))
    {
      auto n = s.find( '=' );
      if (n != s.npos)
        env[ s.substr( 0, n ) ] = s.substr( n+1 );
    }
  }
  // Clean up
  std::remove( foo_bat.c_str() );
  std::remove( foo_out.c_str() );
  // Show the user what we got
  for (auto p : env)
    std::cout << p.first << " : " << p.second << "n";
}

WMIC是控制输出代码页面时的问题程序,因此我们与system()一起使用的怪异管道技巧。

但是,毕竟,您应该直接使用WMI API来获取此类信息。

可能的一个可能,尽管肯定不是理想的解决方案是让批处理文件将其输出写入.txt文件,然后在您的程序中读取该文件。看看这个线程,看看如何做到这一点。