0

所以,我只想检测存储在 args 中的参数列表中的符号“>”,所以我使用 strcmp() 但执行返回我一个分段错误(核心转储)。我还尝试将第一个字符与其 ascii 值进行比较,但它也不起作用。我还有其他方法可以识别字符串中的 > 符号吗?

if(strcmp(argv[1], ">") == 0){

if(execlp("date", "date", NULL) == -1){
    perror("erreur exec");
    exit(EXIT_FAILURE);
}

}
4

1 回答 1

0

编译和链接:

#include <stdio.h>
#include <string.h>


int main(int argc, char *argv[])
{
    for (int i = 0; i < argc; ++i)
        if (strcmp(argv[i], ">") == 0)
            printf("Argument %d is \">\".\n", i);
}

在 macOS 10.14.6 上以 Apple Clang 11.0命名demo并执行命令的示例:

./demo ">"

例如,使用 csh 会导致输出:

参数 1 是“>”。

相反,执行:

./demo > 富

导致终端没有输出,或者foo因为 shell 解析>foo从它传递给程序的参数中省略它们。

于 2020-11-19T19:14:24.963 回答