c - 采用 2 个位置参数的 C 语言示例应用程序

标签 c bash gcc positional-operator

我正在寻找一个简单应用程序的示例,该应用程序将使用 printf 根据位置参数表达两个不同的字符串。

bash 中我会使用:

case $1 in
    -h | --help )           showHelp
                            exit
                            ;;
    * )                     manPipe
                            exit 1
esac

在此之前,我会列出如果运算符(operator)键入 $ foo -h$ foo -help< 将调用名为 showHelp 的函数 进入终端。 $ foo -bar 之类的任何其他内容都会请求调用函数 manPipe

到目前为止我有这段代码:

#include <stdio.h>
#include <cstring>

int secretFunction() {
    printf("Success! You found the secret message!");
}

int main() {

str posParam;
posParam = X;

printf("Enter a number:");
scanf("%s",&posParam);

if ( posParam == "X" ){
    printf("Welcome to app!\nType: " + $0 + " t\nto show a message");
}else{
    if (posParam == "t" ){
        secretFunction();
        }
return 0;
}
return 0;

我知道这段代码真的很糟糕,我试图在 bash 中制作上述代码的示例。我不是要将 bash 脚本 转换为 C 应用程序,而是尝试使用它。我从关于 MD5 checksum 的维基百科文章中得出了我想做的事情的想法。 C 应用程序,它接受一个字符串并为其计算 MD5 校验和。我似乎无法弄清楚他们将位置参数的哪一部分传递给应用程序。

这有点不同,我理解,因为它提示用户提供答案,然后将其赋值。我宁愿在第一个实例中将它用作位置参数。

最佳答案

Bash(等)中的 $1 是 C 程序中的 argv[1]:

#include <stdio.h>

int main(int argc, char *argv[])
{
    if (argc > 1)
    {
        printf("You provided at least one argument (or parameter)\n");
        printf("The first argument is \"%s\"\n", argv[1]);
    }

    return 0;
}

参数 argcargv 数组中有效条目的数量。 argv[0]是可执行文件名,最多可以访问argv[argc - 1]。 (实际上您也可以访问 argv[argv],它始终是一个 NULL 指针)。

关于c - 采用 2 个位置参数的 C 语言示例应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19376325/

相关文章:

bash - 您可以更新 github 项目的 README.md 而无需先手动 fork 吗?

MongoDB shell 查找查询

c++ - 小对象堆栈存储、严格别名规则和未定义行为

c++ - 可变参数模板折叠程序在 gcc9 中失败

c - 为什么这会导致 'struct' 错误?

c - 多线程程序消费者导致程序卡住

C - 用静态数据填充结构的方法

c++ - 指针右侧的调用约定属性

python - 如何使用 Python 打开新的 bash 终端

c - 不正确的寄存器 0x​​104567910 与 '%rbx' 后缀一起使用