0

So I am writing a C++ program that runs a command within the program. Whenever I do run the command though, it outputs a 0 at the end of whatever its supposed to output. Example:

The random int I was thinking of was 130

Where it is only supposed to output The random int I was thinking of was 13 but it still outputs the 0 at the end. Here is my code to run the command:

printf("Running file: %s\n", fileName);
if(!exists(fileName))
{
    printf("That file does not exist.\n");
    return;
}
char buffer [7+strlen(fileName)];
int n;
n = sprintf(buffer, "php -f %s", fileName);
cout << system(buffer) << endl;

I dont think it has anything to do with the php command, because whenever I type into my terminal, php -f <filenamehere> it comes out with the The random int I was thinking of was 13 output. I cannot think of anything else.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Fishy
  • 1,275
  • 1
  • 12
  • 26

2 Answers2

0

The system function returns the "result" of the execution, which is 0 for success, other values for various types of failure (including the result of the executable itself, if applicable).

You are printing that value using cout, which is why it's printing 0 - which is why it's printing 0.

You probably want to do something like this:

int result = system(...);
if (result != 0) 
{
   cout << "system returned " << result << " which means it failed..." << endl;
}

Note that the output of whatever you run using system will go to stdout, it is not returned to the application itself, it is just printed to the console [or wherever stdout is going].

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

system command return only the execution status.

To capture and print the output, see the options in this link

How to execute a command and get output of command within C++ using POSIX?

Community
  • 1
  • 1
Sam Daniel
  • 1,800
  • 12
  • 22