它在 K&R 中。
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
int getline(char *line, int max);
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++;
}
}
}
我不知道这句话是什么意思:if (strstr(line, *argv) != EOF) != expect)
之前有一些错误,我改正了。
然而,当我试图理解它时,我遇到了一些麻烦。
这是我的想法:find -x -n
。所以,argc = 3
。 argv[0] = 查找
。 argv[1] = -x
。 argv[2] = -n
。 argv[3] = NULL
。在第一个 while 循环之后,argc = 0
不应该。所以我很困惑。
最佳答案
示例来自 K&R 第 2 版,第 5.10 节“命令行参数”。
举例说明strstr()
、指针处理,以及向命令行程序添加一些选项:
The standard library function
strstr(s,t)
returns a pointer to the first occurrence of the stringt
in the strings
, orNULL
if there is none. It is declared in<string.h>
.The model can now be elaborated to illustrate further pointer constructions. Suppose we want to allow two optional arguments. One says "print all the lines except those that match the pattern;" the second says "precede each printed line by its line number."
回答您关于以下含义的具体问题:
if ((strstr(line, *argv) != NULL) != except) // note: NULL, not EOF
答案是 strstr()
如果在行中找到作为命令行参数传递的字符串,调用将返回一个非 NULL 指针,否则返回 NULL。所以子表达式
(strstr(line, *argv) != NULL)
评估为:
true - argument is found (a 'match')
false - argument is not found (a 'non-match')
变量except
通过具有以下含义的选项设置:
true - print non-matching lines
false - print matching lines (the default)
因此,完整表达式根据是否包含参数以及是否给出打印匹配或不匹配行的选项来确定是否应打印该行。
关于c - 如何解释这段代码 : if (strstr(line, *argv) != EOF) != except,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32021417/