Cでコマンドラインパラメータにアクセスする方法を学ぶ
あなたの中でCプログラムでは、コマンドの起動時にコマンドラインからパラメータを受け入れる必要がある場合があります。
単純なニーズの場合、そうする必要があるのは変更することだけですmain()
からの関数シグネチャ
int main(void)
に
int main (int argc, char *argv[])
argc
コマンドラインで指定されたパラメーターの数を含む整数です。
argv
はアレイ文字列の。
プログラムの起動時に、これら2つのパラメーターの引数が提供されます。
には常に少なくとも1つのアイテムがあることに注意してください
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