簡體   English   中英

如何在C ++中將批處理文件的輸出讀取為字符串

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

我正在嘗試制作一個小程序,該程序將創建一個批處理文件,在其中執行某些操作,然后從中返回一個字符串,然后刪除該批處理。

我想將批處理文件的輸出存儲在變量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 OFF\nwmic os get caption /value\nwmic path win32_videocontroller get description /value\npause\nexit";
    batch.close();

    system("temp.bat");
    remove("temp.bat");
};

在我的代碼中,我只是將system與批處理文件一起使用。 我想使用cout<<line

我希望稱為line字符串等於批處理文件的輸出。

一種可能的解決方案,盡管公認不是理想的解決方案,是使批處理文件將其輸出寫入.txt文件,然后將該文件讀入程序。 查看此SO線程以了解如何執行此操作。

使用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來獲取此類信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM