Sunday, December 1, 2013

C exercise: run host command and get result with popen()

The function popen() execute command and returning a pointer to the stream which can be used to read the result.
run host command and get result with popen()
run host command and get result with popen()

#include <stdio.h>
#include <stdlib.h>

int main(){
 FILE *result;
 extern FILE *popen();
 char buff[512];
 
 result = popen("df -h", "r");
 if(result){
  int linenumber = 0;
  while(fgets(buff, sizeof(buff), result)!=NULL){
   printf("%d: %s", linenumber, buff);
   linenumber++;
  }
  pclose(result);
  exit(0);
 }else{
  printf("error! ");
  exit(1);
 }
}


Related:
- Run host command with system() without result returned

No comments: