是否有可能从c++中的.exe文件中抓取数据?

is it possible to grab data from an .exe file in c++?

本文关键字:抓取 数据 文件 exe 有可能 c++ 中的 是否      更新时间:2023-10-16

我是C/c++新手,
所以基本上我想调用一个。exe文件,显示2个数字,并能够抓住这两个数字在我的代码中使用它们。为了调用。exe文件,我使用了system命令,但是我仍然无法获取.exe文件

显示的两个数字。
char *files = "MyPathfile.exe";
system (files);

我认为这是更好的方法:这里你只需要创建一个新的进程,然后读取这个进程给你的数据。我在OS X 10.11上用.sh文件进行了测试,效果非常好。我想这可能也适用于Windows。

FILE *fp = popen("path to exe","r");
if (fp == NULL)
{
    std::cout << "Popen is null" << std::endl;
}else
{
    char buff[100];
    while ( fgets( buff, sizeof(buff), fp ) != NULL )
    {
        std::cout << buff;
    }
}

您需要在C++字符串字面量中转义反斜杠,以便:

// note the double "\"
char* files = "MyPath\file.exe";

或者直接使用正斜杠:

char* files = "MyPath/file.exe";

这不是很有效,但你可以用std::system重定向输出到一个文件,然后读取文件:

#include <cstdlib>
#include <fstream>
#include <iostream>
int main()
{
    // redirect > the output to a file called output.txt
    if(std::system("MyPath\file.exe > output.txt") != 0)
    {
        std::cerr << "ERROR: calling systemn";
        return 1; // error code
    }
    // open a file to the output data
    std::ifstream ifs("output.txt");
    if(!ifs.is_open())
    {
        std::cerr << "ERROR: opening output filen";
        return 1; // error code
    }
    int num1, num2;
    if(!(ifs >> num1 >> num2))
    {
        std::cerr << "ERROR: reading numbersn";
        return 1; // error code
    }
    // do something with the numbers here
    std::cout << "num1: " << num1 << 'n';
    std::cout << "num2: " << num2 << 'n';
}

注: (thnx @VermillionAzure)

请注意,系统并不总是在任何地方工作,因为独角兽环境。此外,shell也可以彼此不同,比如cmd.exe和bash。——VermillionAzure

当使用std::system的结果是平台相关的,并不是所有的shell将有重定向或使用相同的语法,甚至存在!