【问题标题】:Using a C++ .exe with C++ : C++ception [duplicate]将 C++ .exe 与 C++ 一起使用:C++ception [重复]
【发布时间】:2013-11-15 16:39:55
【问题描述】:

在这个问题上我需要一些帮助。 我有一个 C++ .exe,我想用 C++ 打开它,然后在控制台中写入一些参数。

这是我想做的一个例子:

让我们假设一个带有此代码的可执行 whatsyourage.exe(实际上,我没有相应的代码):

#include <iostream>

using namespace std;

int main()
{
    int age = 0;
    cout << "What's your age ?" << endl;
    cin >> age;
    cout << "You are " << age << " year !" << endl;
    return 0;
}

我想做类似的事情:

int main()
{std::string invit="21";
std::string chemin ="whatsyourage.exe";// in the same library
std::string const command = chemin+" "+ invit;
system(command.c_str());

}

我想写年龄(21)。

有人可以帮帮我吗?

答案如下:

int main()
{std::string invit="21";
std::string chemin ="whatsyourage.exe";
FILE* pipe = _popen(chemin.c_str(), "w");

    if (pipe == NULL) {
        perror("popen");
        exit(1);
    }
    fputs("30", pipe);// write the age into the pipeline
    pclose(pipe); // close the pipe
 }

【问题讨论】:

    标签: c++ executable


    【解决方案1】:

    POSIX 中的 popen() 函数可以满足您的需求。它允许您在执行程序(如系统)的同时获取其输入/输出流的文件句柄。

    对于 Windows,如果 popen() 不可用,您可以使用 CreatePipe() 和 co 函数来做同样的事情;查看this question 获取一些建议。

    【讨论】:

    • popen() 是 POSIX 特定的。 .exe 对可执行文件的引用表明 OP 正在使用 Windows。
    • 对!我正在添加一个链接到问题“Win32 API 中的 Posix popen() 是什么?”
    • 我会试试的,我会告诉你的!感谢您的快速回答!
    • 好的,它与 popen 完美配合(在带有 windows 的 code::blocks 上)!谢谢大家
    【解决方案2】:

    你添加的第二个sn-p是好的,问题出在第一个代码上。为了从程序处理命令行,您必须将main 定义为int main(int numberOfArguments, char* arguments[])(人们通常使用较短的版本-main(int argc, char* argv[]),但您可以根据需要命名参数)。然后,如果您将参数传递给函数,它将在argv[1] 中,因为argv[0] 始终是可执行文件的路径。所以第一个程序应该是这样的:

    int main(int numberOfArguments, char* arguments[])
    {
       if(numberOfArguments>=2)
          cout << "You are " << arguments[1] << " year !" << endl;
       else
          cout << "Too few arguments passed!" << endl;
       return 0;
    }
    

    【讨论】:

    • 如果我有这个例子中的第一个代码,这将是完美的,但我只有可执行文件。
    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多