来自Kernighan/Ritchie的5.10节命令行参数/可选参数

问题描述:

第一次张贴海报。希望有人能帮助我。在5.10节中,Kernighan给出了一个程序示例,该程序重新打印其中包含字符串的文本行。所以我将它保存为我的文件夹中的“find”,然后进入cmd,然后输入文件夹,然后键入find“-x whatever”。然而由于某些原因,' - '没有注册,它只是将“-x whatever”视为一个长字符串。任何人有任何线索为什么发生这种情况?谢谢。来自Kernighan/Ritchie的5.10节命令行参数/可选参数

#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" 
+0

,当我在 键入'找到-x whatever' 它说FIND:参数格式不正确。如果键入 '找到-x“无所谓”' 它说找不到文件 - -X – 2012-02-27 01:05:09

+0

你可以尝试调用比“找到”其他程序的东西。已经有一个你可能错误地调用的find命令。 – Sean 2012-02-27 03:07:43

+0

哈哈。我想我所做的是我没有构建这个程序,而“发现”是旧命令。哈哈。非常感谢你们。 – 2012-02-27 03:30:34