了解如何在C中访问命令行参数
在你的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
,我们将其作为输出:
./helloIf we pass some random parameters, like this: ./hello a b c
we’d get this output to the terminal:
./hello
a
b
cThis system works great for simple needs. For more complex needs, there are commonly used packages like getopt.
Download my free C Handbook
More clang tutorials:
- Introduction to the C Programming Language
- C Variables and types
- C Constants
- C Operators
- C Conditionals
- How to work with loops in C
- Introduction to C Arrays
- How to determine the length of an array in C
- Introduction to C Strings
- How to find the length of a string in C
- Introduction to C Pointers
- Looping through an array with C
- Booleans in C
- Introduction to C Functions
- How to use NULL in C
- Basic I/O concepts in C
- Double quotes vs single quotes in C
- How to return a string from a C function
- How to solve the implicitly declaring library function warning in C
- How to check a character value in C
- How to print the percentage character using `printf()` in C
- C conversion specifiers and modifiers
- How to access the command line parameters in C
- Scope of variables in C
- Can you nest functions in C?
- Static variables in C
- C Global Variables
- The typedef keyword in C
- C Enumerated Types
- C Structures
- C Header Files
- The C Preprocessor