双截棍 C语言版
linux/unix目录操作的实例

Program Diary -2

perhong posted @ 2008年5月06日 03:22 in C with tags c program diary , 1515 阅读

模拟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.  

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter