C external command output – popen (_popen)

C external command output – popen (_popen)

Прилагам два кода на C, които прихващат резултат от изпълнение на конзолна програма и ред по ред го принтират към стандартния изход:

#include <stdio.h>
#include <stdlib.h>
 
int main( void ){
 
   char   psBuffer[128];
   FILE   *pPipe;
 
   if( (pPipe = _popen( "ping 10.317.112.201", "rt" )) == NULL )
      exit( 1 );
 
   while(fgets(psBuffer, 128, pPipe)) {
      if(strstr(psBuffer,"TTL")) printf("Ima ping\n");
      printf(psBuffer);
   }
 
 
   /* Close pipe and print return value of pPipe. */
   if (feof( pPipe)) {
     printf( "\nProcess returned %d\n", _pclose( pPipe ) );
   }
   else {
     printf( "Error: Failed to read the pipe to the end.\n");
   }
}
#include <stdio.h>
#include <stdlib.h>
 
 
int main( int argc, char *argv[] ){
  FILE *fp;
  int status;
  char path[1035];
 
  /* Open the command for reading. */
  fp = popen("dir ..", "r"); // Dir one directory Up
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit;
  }
 
  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path)-1, fp) != NULL) {
    if(strstr(path,"Edit")){    // check file/dir name contains 'Edit'
        printf("%s", path);
    }
  }
 
  /* close */
  pclose(fp);
 
  return 0;
}

И в двата кода използвам функцията strstr(), която проверява, дали върнатия стринг съдържа определен текст.

Share and Enjoy !

Shares

Leave a Reply

Your email address will not be published. Required fields are marked *

*