home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / OSK / CMDS / mtools_3.6.src.lzh / MTOOLS_3.6 / expand.c < prev    next >
Text File  |  1997-11-13  |  1KB  |  80 lines

  1. /*
  2.  * Do filename expansion with the shell.
  3.  */
  4.  
  5. #define EXPAND_BUF    2048
  6.  
  7. #include "sysincludes.h"
  8. #include "mtools.h"
  9.  
  10. const char *expand(const char *input, char *ans)
  11. {
  12.     int pipefd[2];
  13.     int pid;
  14.     int last;
  15.     char buf[256];
  16.     int status;
  17. #ifdef _OSK
  18.     FILE *fp;
  19. #endif
  20.  
  21.     if (input == NULL)
  22.         return(NULL);
  23.     if (*input == '\0')
  24.         return("");
  25.                     /* any thing to expand? */
  26.     if (!strpbrk(input, "$*(){}[]\\?~")) {
  27.         strcpy(ans, input);
  28.         return(ans);
  29.     }
  30.                     /* popen an echo */
  31.     sprintf(buf, "echo %s", input);
  32.     
  33. #ifndef _OSK
  34.     if(pipe(pipefd)) {
  35.         perror("Could not open expand pipe");
  36.         exit(1);
  37.     }
  38.     switch((pid=fork())){
  39.         case -1:
  40.             perror("Could not fork");
  41.             exit(1);
  42.             break;
  43.         case 0: /* the son */
  44.             close(pipefd[0]);
  45.             destroy_privs();
  46.             close(1);
  47.             dup(pipefd[1]);
  48.             close(pipefd[1]);
  49.             execl("/bin/sh", "sh", "-c", buf, 0);
  50.             break;
  51.         default:
  52.             close(pipefd[1]);
  53.             break;
  54.     }
  55.     last=read(pipefd[0], ans, EXPAND_BUF);
  56.     kill(pid,9);
  57.     wait(&status);
  58.     if(last<0) {
  59.         perror("Pipe read error");
  60.         exit(1);
  61.     }
  62. #else
  63.     fp = popen(buf, "r");
  64.     fgets(ans, EXPAND_BUF, fp);
  65.     pclose(fp);
  66.  
  67.     if (!strlen(ans)) {
  68.         strcpy(ans, input);
  69.         return(ans);
  70.     }
  71.  
  72.     last = strlen(ans) - 1;
  73. #endif
  74.     if(last)
  75.         ans[last-1] = '\0';
  76.     else
  77.         strcpy(ans, input);
  78.     return ans;
  79. }
  80.