7

十三、命令行参数

 2 years ago
source link: https://www.techstack.tech/post/%E5%8D%81%E4%B8%89%E3%80%81%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%8F%82%E6%95%B0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

十三、命令行参数

发表于2021-12-24|更新于2021-12-24|C语言入门手册
字数总计:394|阅读时长:1分钟|阅读量:1|评论数:0

在 C 程序中,你可能需要在命令启动时从命令行接收参数。

对于简单的需求而言,你只需要将 main() 函数的签名从

int main(void)
int main (int argc, char *argv[])

argc 是一个整数,包含从命令行提供的参数的数量。

argv 是一个字符串数组。

当程序开始运行时,我们用这两个参数给主函数提供参数。

注意 argv 数组中总是至少有一个元素:程序的名字。

咱们以我们用来运行程序的 C 编译器作为示例吧,就像这样:

gcc hello.c -o hello

如果这就是我们的程序,我们的 argc 将会是 4,argv 将是一个包含以下内容的数组:

  • gcc
  • hello.c
  • -o
  • hello

咱们写一个打印它收到的参数的程序吧:

#include <stdio.h>

int main (int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
}

如果我们的程序名为 hello,并且我们像这样运行它:./hello,我们就会得到以下输出:

./hello

如果我们传递一些随机参数,就像这样:./hello a b c,我们竟会在终端中得到这个输出:

./hello
a
b
c

对于简单的需求而言,这个系统工作得很好。对于更加复杂的需求,有一些常用的包,比如 getopt


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK