【问题标题】:Iterating through options of ls program from the command line从命令行迭代 ls 程序的选项
【发布时间】:2020-08-06 09:22:37
【问题描述】:

我正在编写一个带有一些选项的自定义版本的 ls 程序。选项可以输入为“-i”或类似“-ilR”。我的这部分代码遍历命令行参数并相应地设置一个结构。除非我使用“./myProgram -i Directory”运行程序,否则它不会进入我设置的测试打印。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/fcntl.h>
#include <stdbool.h>
#include <string.h>

struct optionArguments{
    bool argumenti;
    bool argumentl;
    bool argumentR; 
};

int main(int argc, char* argv[]){

    struct optionArguments options;
        options.argumenti = false;
        options.argumentl = false;
        options.argumentR = false;

   
    for(int i = 1; i<argc-2; i++){
        for(int j = 0; j<strlen(argv[i]); j++){
            char chr = argv[i][j];
            if(chr == 'i'){
                options.argumenti = true;
            }
            if(chr == "l"){
                options.argumentl = true;
            }
             if(chr == "R"){
                options.argumentR = true;
            }
        }
    }

    if(options.argumenti){
        printf("OPTION I\n");
    }
}

非常感谢任何帮助/建议

编辑:我只是在第二个循环中放置了一个测试打印,它根本不打印任何东西,所以第二个循环甚至没有运行。

【问题讨论】:

  • 为什么是i &lt; argc-2
  • 您是否尝试过调试(甚至使用打印)来查看您正在查看的值以及正在执行的代码的哪些位?
  • 你不能使用==来比较C语言中的字符串,或者一个char和一个字符串。
  • @Shawn 不过,您可以将字符与带有== 的字符进行比较,看起来这就是 OP 试图做的。双引号而不是单引号看起来像是拼写错误,因为它们第一次使用单引号。
  • 尝试打印 argc - 也许这不是您所期望的 (3 args, argc -2, 1

标签: c command-line-arguments ls


【解决方案1】:

如果你使用设计用于处理命令行参数解析的getopt()函数会简单得多。

注意:由于您已经包含 unistd 库,因此使用 getopt 会更明智,否则,还有其他可用的实现,例如 argp()

这是一个使用来自 POSIX C 库 unistdgetopt 的程序

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/fcntl.h>
#include <stdbool.h>
#include <string.h>

struct optionArguments{
    bool argumenti;
    bool argumentl;
    bool argumentR; 
};

int main(int argc, char* argv[]){

    struct optionArguments options;
        options.argumenti = false;
        options.argumentl = false;
        options.argumentR = false;

    int opt;
    while ((opt = getopt(argc, argv, "ilR")) != -1) {
        switch (opt) {
        case 'i': options.argumenti = true; break;
        case 'l': options.argumentl = true; break;
        case 'R': options.argumentR = true; break;
        default:
            fprintf(stderr, "Usage: %s [-ilR] \n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }


    if(options.argumenti){
        printf("OPTION I\n");
    }
    if(options.argumentl){
        printf("OPTION l\n");
    }
    if(options.argumentR){
        printf("OPTION R\n");
    }
}

其他实现方式请访问:Parsing command-line arguments in C?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 2018-01-03
    • 2014-01-12
    • 1970-01-01
    相关资源
    最近更新 更多