home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / REDIRECT.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  100 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  REDIRECT.C - Posix-compliant utilities to handle redirection
  5. **
  6. **  written by Benno Sauer, Vienna, 1991
  7. **  released into public domain
  8. */
  9.  
  10. #include <stdio.h>
  11. #include <fcntl.h>
  12. #include <sys\stat.h>
  13.  
  14. #if defined(MSDOS) || defined(__MSDOS__)
  15.  #include "unistd.h"
  16. #else
  17.  #include <unistd.h>
  18. #endif
  19. #include "dirport.h"
  20. #include "snpdosys.h"
  21.  
  22. /*
  23. **  Use these predefined structures for the 3 primary streams.
  24. **  Define others (e.g. stdprn under DOS) as required.
  25. */
  26.  
  27. REDIR_STRUCT redir_stdin, redir_stdout, redir_stderr;
  28.  
  29.  
  30.  
  31. void  start_redirect ( REDIR_STRUCT *s )
  32. {
  33.       if (s->which == fileno(stdin))
  34.             s->what = open ( s->path, O_RDWR, S_IREAD );
  35.       else  s->what = open ( s->path, O_CREAT | O_RDWR, S_IREAD | S_IWRITE );
  36.  
  37.       s->oldhandle = dup ( s->which );
  38.  
  39.       dup2  ( s->what, s->which );
  40.       close ( s->what );
  41.       s->flag = 1;
  42. }
  43.  
  44. void  stop_redirect ( REDIR_STRUCT *s )
  45. {
  46.       if ( s->flag )
  47.       {
  48.             dup2 ( s->oldhandle, s->which );
  49.             close ( s->oldhandle );
  50.             s->flag = 0;
  51.       }
  52. }
  53.  
  54. #ifdef TEST
  55.  
  56. #include <string.h>
  57.  
  58. main()
  59. {
  60.       char line[132];
  61.       int i;
  62.  
  63.       strcpy(redir_stdin.path, "redirect.c");
  64.       redir_stdin.which = fileno(stdin);
  65.  
  66.       strcpy(redir_stdout.path, "x-file");
  67.       redir_stdout.which = fileno(stdout);
  68.  
  69.       strcpy(redir_stderr.path, "file.x");
  70.       redir_stderr.which = fileno(stderr);
  71.  
  72.       start_redirect(&redir_stdin);
  73.       start_redirect(&redir_stdout);
  74.       start_redirect(&redir_stderr);
  75.  
  76.       for (i = 1; !feof(stdin); ++i)
  77.       {
  78.             if (fgets(line, 132, stdin))
  79.             {
  80.                   fputs(line, stdout);
  81.                   fprintf(stderr, "Read line #%d\n", i);
  82.             }
  83.       }
  84.       fflush(stdout);
  85.       fflush(stderr);
  86.  
  87.       stop_redirect(&redir_stdin);
  88.       stop_redirect(&redir_stdout);
  89.       stop_redirect(&redir_stderr);
  90.  
  91.       fputs("All done!\n", stdout);
  92.       fflush(stdout);
  93.       fputs("Hit Enter to exit\n", stderr);
  94.       getchar();
  95.  
  96.       return 0;
  97. }
  98.  
  99. #endif /* TEST */
  100.