Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222463
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-23 09:04:32

  1. /* k&r(5.10): Command-line Arguments
  2.    created on Mar 23, 2011
  3.    */
  4. #include "stdio.h"
  5. #include "string.h"
  6. #define MAXLINE 1000

  7. int getline1(char *line, int max);

  8. /* find: print lines that match pattern from 1st arg */
  9. main(int argc, char *argv[])
  10. {
  11.     char line[MAXLINE];
  12.     int found = 0;

  13.     if (argc != 2)
  14.      printf("Usage: find pattern\n");
  15.     else
  16.      while (getline1(line, MAXLINE) > 0)
  17.         /* strstr(s,t): return a pointer to the first occurrence
  18.          of the string t in the string s, or NULL if there is none. */
  19.         if (strstr(line, argv[1]) != NULL) {
  20.             printf("%s", line);
  21.             found++;
  22.         }
  23.     return found;
  24. }

  25. /* find: print lines that match pattern from 1st arg,  
  26. improve version; find -n -x pattern, -n for print number of line; -x for except pattern. */
  27. main(int argc, char *argv[])
  28. {
  29.     char line[MAXLINE];
  30.     long lineno = 0;
  31.     int c, except = 0, number = 0, found = 0;

  32.     while (--argc > 0 && (*++argv)[0] == '-')
  33.      while (c = *++argv[0]) //impcrements the pointer argv[0]
  34.         switch (c) {
  35.             case 'x':
  36.                 except = 1;
  37.                 break;
  38.             case 'n':
  39.                 number = 1;
  40.                 break;
  41.             default:
  42.                 printf("find: illegal option %c\n", c);
  43.                 argc = 0;
  44.                 found = -1;
  45.                 break;
  46.         }

  47.     if (argc != 1)
  48.      printf("Usage: find -x -n pattern\n");
  49.     else
  50.      while (getline1(line, MAXLINE) > 0) {
  51.         lineno++;
  52.         /* strstr(s,t): return a pointer to the first occurrence
  53.          of the string t in the string s, or NULL if there is none. */
  54.         if ((strstr(line, *argv) != NULL) != except) {
  55.             if (number)
  56.              printf("%ld:", lineno);
  57.             printf("%s", line);
  58.             found++;
  59.         }
  60. }
  61. return found;
  62. }

  63. /* getline: return the number of lines of input */
  64. int getline1(char *line, int max)
  65. {
  66.     int i, c;
  67.     i = 0;

  68.     for (i = 0; i < max-1 && (c=getchar()) != EOF && c != '\n'; i++)
  69.      line[i] = c;
  70.     if (c = '\n')
  71.      line[i++] = c;
  72.     line[i] = '\0';
  73.     return i;
  74. }
阅读(763) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~