c - 如何在 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
}
}
解决方案
您可以使用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)
。
推荐阅读
- angular - Cross-Origin Request Blocked Angular 4,POST Request
- java - Generate array with random numbers
- ruby - 我可以选择关闭公用文件夹下的默认页面吗?
- r - Running raster::stackApply() function in parallel
- go - 只读来自 HTTP 处理程序的共享结构时如何防止竞争条件
- swagger - Swagger - 逗号分隔的参数列表
- javascript - 如何将 Github 所见即所得编辑器导入 HTML?
- jquery - Angular Universal 和 jQuery(在服务器上忽略 $)
- sql-server - SSIS CozyRoc SFTP 下载文件今天修改
- ruby-on-rails - ActiveRecord 对最后一个空值和按次要属性排序的非空值的关系进行排序