首页 > 解决方案 > 如何在 C 中分别读取标志和文件名?(基于 WC 实用程序)

问题描述

假设我有:./some_app (flags) (文本文件)

有一些要使用的标志(如可选标志)和一些要使用的文本文件

一些进一步的示例用法:

./some_app -l -c -w foo.txt bar.txt

./some_app -l -c -w -r foo.txt bar.txt

我已经知道如何处理命令标志,但因为它们是单独的循环:我在这部分很烂

for (int i = argc; i < argc; i++) //Loop over the filename arguments./some_app -c -l -w -n ex/foo.txt ex/bar.txt
{
    FILE *file_fp = fopen(argv[i], "r");
    if ((file_fp == NULL))
    {
        fprintf(stderr, "%s: No such file or directory\n", argv[i]);
        return 0;
    }
    else
    {
       use get opts in a switch case using getline
    }
}

标签: ccommand-line-argumentsgetopt

解决方案


您可以使用getopt(3)解析命令行:

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

int main(int argc, char **argv)
{
    int opt;
    while ((opt = getopt(argc, argv, "lcwr")) != EOF) {
        switch(opt) {
        case 'l': printf("option -l processed\n"); break;
        case 'c': printf("option -c processed\n"); break;
        case 'w': printf("option -w processed\n"); break;
        case 'r': printf("option -r processed\n"); break;
        }
    }
    /* shift the args */
    argc -= optind;
    argv += optind;
    /* process the files */
    if (argc == 0) {
        printf("No arguments\n");
    } else {
        int i;
        for (i = 0; i < argc; i++) {
            printf("Argument [%d] = \"%s\"\n",
                 i, argv[i]);
        }
    }
    return EXIT_SUCCESS;
}

getopt(3)几乎存在于任何 C 实现中以允许命令行处理。阅读手册页getopt(3)


推荐阅读