home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc_prog / chap10 / ccopy2.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-04-06  |  1.5 KB  |  61 lines

  1. /* ccopy2.c  -- copies a file, cutting blank lines and    */
  2. /*              leading space from lines of copy          */
  3.  
  4. /*              Modified to demonstrate stdout and stderr */
  5.  
  6. #include <stdio.h>        /* for FILE, BUFSIZ, NULL */
  7. #include <ctype.h>        /* for iswhite()          */
  8.  
  9. main(argc, argv)
  10. int argc;
  11. char *argv[];
  12. {
  13.     FILE *fp_in, *fp_out;
  14.     char buf[BUFSIZ];
  15.     char *cp;
  16.  
  17.     if (argc < 2)
  18.         {
  19.         fprintf(stderr, "usage: ccopy infile {outfile}\n");
  20.         exit(1);
  21.         }
  22.     if ((fp_in = fopen(argv[1], "r")) == NULL)
  23.         {
  24.         fprintf(stderr, "\"%s\": Can't open.\n", argv[1]);
  25.         exit(1);
  26.         }
  27.     if (argc == 3)
  28.         {
  29.         if ((fp_out = fopen(argv[2], "w")) == NULL)
  30.             {
  31.             fprintf(stderr, "\"%s\": Can't open.\n", argv[2]);
  32.             exit(1);
  33.             }
  34.         }
  35.     else
  36.         fp_out = stdout;
  37.  
  38.     while (fgets(buf, BUFSIZ, fp_in) != NULL)
  39.         {
  40.         cp = buf;
  41.         if (*cp == '\n')    /* blank line */
  42.             continue;
  43.         while (isspace(*cp))
  44.             {
  45.             ++cp;
  46.             }
  47.         if (*cp == '\0')    /* empty line */
  48.             continue;
  49.         if (fputs(cp, fp_out) == EOF)
  50.             {
  51.             fprintf(stderr, "Error writing.\n");
  52.             exit(1);
  53.             }
  54.         }
  55.     if (! feof(fp_in))      /* error reading? */
  56.         {
  57.         fprintf(stderr, "\"%s\": Error reading.\n", argv[1]);
  58.         exit(1);
  59.         }
  60. }
  61.