Datei: p7-11.c


    1   /*
    2    *      Beispielprogramm 11, Abschnitt 7
    3    *      Programm zum Finden von Zeilen, die ein anzugebendes
    4    *      Suchmuster enthalten bzw. nicht enthalten
    5    *      Aufruf: find [-n] [-x] suchmuster 
    6    */
    7    
    8   #include <stdio.h>
    9   
   10   #define MAXLINE 1000
   11   
   12   int getline(char [], int);
   13   int index(char [], char []);
   14   
   15   void main(int argc, char *argv[])
   16   {
   17     char line[MAXLINE], *s;
   18     long lineno = 0;
   19     int except = 0, number = 0;
   20     
   21     while (--argc > 0 && (*++argv)[0] == '-')
   22       for (s = argv[0]+1; *s != '\0'; s++)
   23         switch (*s) {
   24   	case 'x':
   25   	  except = 1;
   26   	  break;
   27   	case 'n':
   28   	  number = 1;
   29   	  break;
   30   	default:
   31   	  printf("find: illegal option %c\n",*s);
   32   	  argc = 0;
   33   	  break;
   34         }
   35   
   36     if (argc != 1)
   37       printf("Usage: find [-x] [-n] pattern\n");
   38     else
   39       while (getline(line, MAXLINE) > 0) {
   40         lineno++;
   41         if ((index(line, *argv) >= 0) != except) {
   42   	if (number)
   43   	  printf("%ld: ",lineno);
   44   	printf("%s",line);
   45         }
   46       }
   47   
   48   } /* main() */
   49   
   50   /* Zeile in s ablegen, Laenge liefern */
   51   int getline(char s[], int lim)
   52   { 
   53     int c, i;
   54     
   55     i = 0;
   56     while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
   57       s[i++] = c;
   58     if (c == '\n')
   59       s[i++] = c;
   60     s[i] = '\0';
   61     return(i);
   62   
   63   } /* getline() */
   64   
   65   /* Position von t in s liefern, -1 falls nicht da */
   66   int index (char s[], char t[])    
   67   { 
   68     int i, j, k;
   69     
   70     for (i = 0; s[i] != '\0'; i++) {
   71       for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
   72         ;
   73       if (t[k] == '\0')
   74         return(i);
   75     }
   76     return(-1);
   77     
   78   } /* index() */


Erzeugt von c2html 1.01