c - 如何解释这段代码 : if (strstr(line, *argv) != EOF) != except

标签 c arrays string pointers argv

它在 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 = 3argv[0] = 查找argv[1] = -xargv[2] = -nargv[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 string t in the string s, or NULL 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/

相关文章:

Java 2D数组,可以设置单独的大小吗?

c++ - 在没有手动分配缓冲区的情况下使用 sprintf

c# - 变量初始化不安全?

c - Frama-C\strlen 函数

c - 将 char 数组拆分为分隔符为 NUL char 的标记

c - 根据列合并两个文件并排序

检查数组的出现次数并输出到新数组。 C

c - 指向数组的 typedef 的指针

c++ - 为什么我不能将字符串传递给函数 GetDriveTypesA()?

java - 在java中将 int 1 转换为字符串 'one' 、 2 转换为 'two' 等时出现问题