How do I get the answer of a system call that is printed in the terminal?
for example:
I execute system("pwd");
and get the answer /home/user/
But because I need to send this result to somewhere, I need to store it in a string.
Thanks in advance.
How do I get the answer of a system call that is printed in the terminal?
for example:
I execute system("pwd");
and get the answer /home/user/
But because I need to send this result to somewhere, I need to store it in a string.
Thanks in advance.
Use popen() instead.
Instead of what?
I do not create or open a file. All I need is to get the answer of any command from the command line into a string, "pwd" is just an example.
Can you please give a simple example?
Situation: I have
char command[50] = "ls";
system(command); // executes the string
___________________?
you can use popen following way:
#include <stdio.h>
int main()
{
#define BUFSIZE 1024
char buf[1024];
FILE *fp = NULL;
char *cmd = "ls -al /home/";
int nbytes = 0;
int fbytes = BUFSIZE;
int ch =0;
fp = popen(cmd, "r");
if (fp == NULL) {
printf("unable to open %s", cmd);
exit(0);
}
while (nbytes < fbytes && (ch = fgetc(fp)) != EOF)
buf[nbytes++] = ch;
buf[nbytes] = 0;
pclose(fp);
printf("output for %s %d:\n %s", cmd , nbytes, buf);
return 0;
}
thanks for answering
it works for some commands for example pwd, ifconfig, netstat, etc; but it does not get some answers such as "No such file or directory" when I used "gcc nonExistent.c" or "route help".
Any ideas?
netstat, ifconfig are not in your PATH. Try with providing full path or Might be you need supreuser permissions.
First try these commands on your promopt/shell.
Actually the problem is that you are getting those messages on standard error, not standard output. Try popen3 if your system has that.