Program Diary -2

Posted on 2008年5月06日 03:22

模拟grep简单命令

 

  1. #include <stdio.h>
  2. #define MAXLINE 10000   /*最大输入的行*/
  3.  
  4.  
  5. int getline(char line[],int max);
  6. int strindex(char source[],char searchfor[]);
  7.  
  8. char pattern[] = "ould";        /*待查找的模式*/
  9.  
  10.  
  11. int main(void)
  12. {
  13.  char line[MAXLINE];
  14.  int found = 0;
  15.  
  16.  while (getline(line, MAXLINE) > 0)
  17.        if (strindex(line, pattern) >= 0) {
  18.           printf("%s", line);
  19.           found++;                   
  20.        }
  21.        return found;
  22. }
  23.  
  24.  
  25. int getline(char s[],int lim)
  26. {
  27.  int i, c;
  28.  i = 0;
  29.  while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
  30.        s[i++] = c;
  31.  if(c == '\n')
  32.       s[i++] = c;
  33.  s[i] = '\0';
  34.  return i;   
  35. }
  36.  
  37.  
  38. int strindex(char s[],char t[])
  39. {
  40.  int i, j, k;
  41.  
  42.  for (i = 0; s[i] != '\0'; i++) {
  43.      for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
  44.          ;
  45.      if(k > 0 && t[k] == '\0')
  46.           return i;
  47.  }
  48.  return -1;
  49. }
  50.  

 

Program Diary-1

Posted on 2008年5月02日 06:11

打印输入各个字符出现频度的直方图:

  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. #define MAXHIST 15
  5. #define MAXCHAR 128
  6.  
  7. int main(void)
  8. {
  9.         int c, i;
  10.         int len;        /* length of histogram    */
  11.         int maxvalue;   /* max different characters        */
  12.         int cc[MAXCHAR];
  13.  
  14.         for(i = 0; i < MAXCHAR; ++i)
  15.                 cc[i] = 0;
  16.         while((c = getchar()) != EOF)
  17.                 if (c < MAXCHAR)
  18.                         ++cc[c];
  19.         maxvalue = 0;
  20.         for(i = 1; i < MAXCHAR; i++)
  21.                 if (cc[i] > maxvalue)
  22.                         maxvalue = cc[i];
  23.  
  24.         for(i = 1; i < MAXCHAR; ++i){
  25.                 if (isprint(i))
  26.                         printf("%5d - %c - %5d : ", i, i, cc[i]);
  27.                 else
  28.                         printf("%5d -   - %5d : ", i, cc[i]);
  29.                 if (cc[i] > 0) {
  30.                         if ((len = cc[i] * MAXHIST / maxvalue) <= 0)
  31.                                 len = 1;
  32.                 } else
  33.                         len = 0;
  34.                 while (len > 0) {
  35.                         putchar('*');
  36.                         len--;
  37.                 }
  38.                 putchar('\n');
  39.         }
  40.         exit(1);
  41.  
  42. }