2

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);
}
Zong
  • 6,160
  • 5
  • 32
  • 46
ChawBawwa
  • 43
  • 1
  • 5
  • `system()` is not a command, it's a function. "zero or a numerical value" - so zero is not a number, right? Also, you should have done some research using google or SO's own searching facility - this has already been asked literally tens of times. –  Dec 06 '13 at 19:21
  • This question appears to be off-topic because it doesn't demonstrate research. –  Dec 06 '13 at 19:21
  • i did a 2 hours research using google and i ddint found the way i want it and considering your reputation can you just point out one of the same previously asked questions if you can find – ChawBawwa Dec 06 '13 at 19:34

1 Answers1

2

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++?

Community
  • 1
  • 1
shanet
  • 7,246
  • 3
  • 34
  • 46
  • Actually i want to run any shell commands not just the "ls" command but is it possible to get the same thing with popen?? – ChawBawwa Dec 06 '13 at 19:31
  • Yes, the first argument to `popen` is the program to run. Replace "ls" with whatever program you want to run. – shanet Dec 06 '13 at 19:51