Reputation: 43
I'm trying to run the system()
command in C. But I want the output to be stored in a string variable but later I found that the return value of system command is zero or a numerical value. As an example if I put system(ls)
the result will be printed in the shell, but what I want is to take that to a string. Is it possible?
If that is not possible, can someone tell me how to direct the output of system()
command to a file so i can read it from the file.
while(1){
bzero(buff,MAXLINE+1);
read(ns,buff,MAXLINE);
puts(buff);
system(buff);
send(ns,buff,strlen(buff)+1,0);
}
The above code doesn't put the output of system command to a string so I tried to put the output to a text file which also didn't work:
while(1){
FILE *f=fopen("tmp.txt","w");
bzero(buff,MAXLINE+1);
read(ns,buff,MAXLINE);
system(buff>f);
puts(buff);
send(ns,buff,strlen(buff)+1,0);
}
Upvotes: 2
Views: 3052
Reputation: 7324
You should use popen()
instead of system()
if you want to capture the process output (really you should never use system()
).
Quick example:
FILE *fd = popen("ls", "r");
if(fd == NULL) {
fprintf(stderr, "Could not open pipe.\n");
return;
}
// Read process output
char buffer[BUFFER];
fgets(buffer, BUFFER, fd);
http://linux.die.net/man/3/popen
I should note, however, that there are much more appropriate ways of getting a directory listing than executing ls
from your program. Here's a question dealing with that topic: How can I get the list of files in a directory using C or C++?
Upvotes: 2