0

I need some help on this subject. I have a C++ .exe that I want to open with C++ and then write some arguments in the console.

Here is an example of what I want to do:

Lets assume an executable whatsyourage.exe with this code (in reallity, I don't have the corresponding code):

#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;
}

and I want to do something like:

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());

}

I want to write the age (21).

Can someone please help me?

Here is the answer:

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
 }

2 Answers2

1

The popen() function from POSIX does what you are looking for. It allows you to execute a program (like system) while getting a file handle on its input/output streams.

For Windows, if popen() is not available, you can use the CreatePipe() & co functions to do the same thing; check out this question for some pointers.

Community
  • 1
  • 1
remram
  • 4,805
  • 1
  • 29
  • 42
0

The second snippet you added is good, and the problem is with the first code. In order to handle the command line from a program, you have to define the main as int main(int numberOfArguments, char* arguments[]) (often people use the shorter version - main(int argc, char* argv[]), but you can name the arguments as you wish). Then, if you pass an argument to the function, it will be in argv[1], since argv[0] is always the path to the executable. So the first program should look like this:

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;
}
Paweł Stawarz
  • 3,952
  • 2
  • 17
  • 26