c - Kernighan/Ritchie 的第 5.10 节命令行参数/可选参数

标签 c optional-parameters kernighan-and-ritchie

第一次海报。希望有人能帮我解决这个问题。在 5.10 节中,Kernighan 给出了一个程序示例,该程序重新打印其中包含字符串的文本行。所以我将其保存为我的文件夹中的“查找”,然后进入 cmd,然后进入文件夹,然后键入查找“-x whatever”。然而由于某种原因,'-' 没有注册,它只是将“-x whatever”视为一个长字符串。任何人都知道为什么会这样吗?谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 1000

int getline(char *s, int lim)
{
int i = 0;

while(i < lim - 1 && (*s = getchar()) != EOF && *s++ != '\n')
   i++;

if(*s == '\n')
  *s++ = '\n', i++;

*s = '\0';
return i;
}
int main(int argc, char *argv[])
{

 char line[MAXLINE];
 long lineno = 0;
 int c, except = 0, number = 0, found = 0;

 while(--argc > 0 && (*++argv)[0] == '-')
    while(c = *++argv[0])
      switch(c) {
         case 'x':
              except = 1;
              break;
         case 'n':
              number = 1;
              break;
         default:
              printf("find: illegal option %c\n", c);
              argc = 0;
              found = -1;
              break;
      }

 if(argc != 1)
     printf("Usage: find -x -n pattern\n");
 else
     while(getline(line, MAXLINE) > 0) {
         lineno++;
         if((strstr(line, *argv) != NULL) != except) {
               if(number)
                  printf("%ld:", lineno);
               printf("%s", line);
               found++;
         }
     }

 printf("Found: %d", found);
 return found;
}

最佳答案

你必须输入

  find -x whatever

代替

  find "-x whatever"

关于c - Kernighan/Ritchie 的第 5.10 节命令行参数/可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9458381/

相关文章:

c - 快速排序不适用于最后两个数字

c - 如何在函数文件和项目文件中正确包含自己的库

编译器需要在第一列添加 # 吗?

c - 在 C 中使用寄存器变量的一个很好的例子是什么?

c - 如何在 Windows 上编译 C 完美最小哈希库?

c++ - printf 中的优先级似乎发生了变化

c - 如何在 OpenCV 中将多个图像作为命令行参数加载到 sprintf() 和 cvLoadImage()...?

maven命令行如何为单个命令指向特定的settings.xml?

c# - 使用函数定义可选参数

c# - C++ 空指针参数作为 C# 中的可选参数替代