如何将批处理文件的输出读取到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 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文件,然后在您的程序中读取该文件。看看这个线程,看看如何做到这一点。
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何从字符串C++读取多个整数
- 使用字符串读取的字符串
- 从文件到字符串读取并传递到功能
- C++ cin 将字符串读取到 int 类型中返回 0
- 使用CIN和/或字符串读取带有混合输入的文本文件
- 将两个字符串作为一个字符串读取
- 如何将WCP 1252字符串读取为std::tstring
- 如何将字符串读取为字符串向量或将整数读取为整数向量
- 将一系列字符串读取到char数组中
- 如何在 c++ 中将文件中的段落作为单个字符串读取
- 从 txt 文件中将后缀表达式作为字符串读取
- C++银行项目;如何将一组字符串读取为单独的浮点数并添加它们
- 在 c++ 中循环字符串读取器
- 将字符串读取为命令行参数C++
- 如何在QT中使用QDomDocument对象将字符串读取为XML
- 使用Matio库将.mat文件中的字符串读取到C++中
- 作为字符串读取第一列数据文件
- 如何在字符串读取完成时停止c++的recv() ?