Linux console commands in C++ (gcc compiler)
How do I issue a command from my C++ program to the Linux console (Ubuntu) and assign the value my command tells me to a string variable? Please give me an example where the program gives the simple command “uname -a” to console and write the result.
Sorry my English is not good, I know very little. I would be glad if someone wrote his answer in Russian (if it was allowed). I looked for answers to my questions in Russian resources, but to nothing, you are my last hope.
Solution
The command you need is popen
. You can get information about it by typing man popen
in the shell; If your Linux distribution runs its Russian translation, it should display information about it in Russian.
Basically, popen
simply opens a “file” (stream) that you can use just like a regular file. Here are examples of how to use it:
#include <stdio.h>
int main()
{
FILE *f;
char stuff[100];
f = popen("uname -a", "r");
fgets(stuff, 100, f);
printf("%s", stuff);
pclose(f);
}
The code above doesn’t have any error handling; You should insert the appropriate check after reading and understanding the complete manual page ( rus)。