接受Stdin或CLI参数的设计模式

Design pattern for accepting stdin OR CLI arguments

本文关键字:设计模式 参数 CLI Stdin 接受      更新时间:2023-10-16

对于C ,我如何接受CLI参数 stdin?

例如,假设我有一个函数foo(),我想调用一个可变数量的参数。对于标准ARG,我只使用以下内容:

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cout << "usage goes here.n";
    } else {
        for (int i; i < argc; ++i) {
            foo(argv[i]);
        }
    }
}

但是,如果他们通过stdin将它们发送给我并将参数运送到我的应用程序怎么办?有没有办法检测和接受/处理/处理两者?在现代C (C 11及以后)中,有效的设计模式是什么?

我对设计模式/示例实现感兴趣。请随时参考执行此操作的库(Boost?),但请分享/解释一个示例实现。

通常,您只会从stdin读取输入,而不是参数/选项。通过阅读和评估参数/选项,该程序应确定该程序是否期望来自STDIN或E.G.的输入。文件参数。

作为GREP的手册的例如:

概要

grep [options]模式[file ...]

描述

GREP搜索命名命名的命名输入文件(或标准输入命名,或者给出了单个连字符>连字符( - )作为文件名)包含与给定模式匹配的行。

缺少文件参数或 - 选项指示 grep 读取stdin。

您的程序的调用可能看起来像这样,缺乏文件参数表明从stdin读取输入:

# file argument, input is in the file
command -o someoption filename
# file content supplied via stdin
command -o someoption < filename     
# with pipe and - (stdin) as file argument
othercommand | command -o someoption -

用于解析选项/参数Boost具有程序选项库