c - 如何获取前面没有 '-' 或 '--' 的参数

标签 c command-line command-line-arguments

我有一个程序需要以下形式的命令行参数:

./my_program -m256M -tm -t some_other_file

“some_other_file”参数未绑定(bind)到 -t(-t 它只是另一个功能)所以我不能将它作为任何标志的 optarg,我也不能假设它是列表中的最后一个参数.

我该怎么做?

谢谢

最佳答案

getopt(_long) 以这种方式置换 argv 中的参数,当没有参数时它理解剩下(当它返回 -1 时)所有已解析的参数都在未解析的参数之前。因此,您可以使用全局变量 optind,getopt 将其设置为 argv 中第一个参数的索引,它没有解析该参数以便为您的程序找到任何其他参数。假设除了 getopt 已知的参数之外还有一个这样的 some_other_file,伪代码将是:

while ((ret = getopt_long(argc, argv, ...)) != -1) {
    /* do something with ret */
}
if (optind >= argc) {
    /* error, no some_other_file */
} else {
    file_str = argv[optind];
    /* do something else */
}

此方法可以扩展到任意数量的无连字符参数,这些参数保证全部保留在 argv 中,以便将它们传递给程序,并且所有参数都在 getopt 理解的任何参数之后,所以一个简单的从 optind 到 argc-1 的循环可用于列出这些未解析的参数。

关于c - 如何获取前面没有 '-' 或 '--' 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2648503/

相关文章:

c - 发送数据包(PCAP、WLAN、C)给接收方,无连接接收

c - 如何在 1 个循环中打印 2 个 double 组,第二个数组应该是第一个数组的元素的累积总数?

php - 不一致的视频转换

haskell - optparse-applicative : Generate usage information with custom error message from options definition

c++ - lua - 在 C 中存储闭包,在 C 中调用异步

c - 指向 int 类型数组的指针的大小是多少?

c# - .NET : Reading the command prompt output

sql-server - osql、isql 和 sqlcmd 之间有什么区别?

go - Go 中的命令行标志可以设置为强制吗?

wix - 使用 WiX Burn 静默安装 SqlLocalDB.msi #EDIT3