Tuesday, December 5, 2023

How to invoke operating system command from a C/C++ program.

There can be situations in where we need to excute a linux commands from a C++ program.

Then system() is the function you need.

It is simple, only the command has to be passed and it will return 0 if command successfuly executed, 1 otherwise.

syntax: int system(const char *command);

As system function is declared in stdlib.h, it can be considered a C function. But in C++, stdlib.h is merged into the std namespace and is located in the cstdlib .
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int returnCode = system("nm -C -S -n mylib.so > libSymbols.log");
if (returnCode == 0) {
cout << "Command executed successfully." << endl;
}
else {
cout << "Command execution failed" << returnCode << endl;
}
return 0;
}
view raw system.cpp hosted with ❤ by GitHub

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...