- 1. getopt
- 2. sleep
1. getopt
コマンドラインの引数リストから、オプション文字を取得します。
#include <unistd.h>
extern char *optarg;
extern int optind;
extern int optopt;
extern int opterr;
extern int optreset;
int getopt(int argc, char * const *argv, const char *optstring);
通常、1番目と2番目の引数には、main で受け取る引数をそのまま渡します。
3番目の引数には、オプションとして許す文字を列挙します。
文字の後ろに :(コロン)がある場合、そのオプションはさらに引数を必要とし、その引数は optarg 内に入ります。
下記のソースを書いて。
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int ch;
while ((ch = getopt(argc, argv, "ab:")) != -1)
{
printf("optind[%d] optarg[%s] ", optind, optarg);
switch (ch)
{
case 'a':
printf("a オプションあり\n");
break;
case 'b':
printf("b オプションあり\n");
break;
default:
printf("[%c] オプション指定\n", ch);
break;
}
}
return 0;
}
引数を試すと以下のようになります(a.out は実行モジュールです)。
$ ./a.out
$ ./a.out -a
optind[2] optarg[(null)] a オプションあり
$ ./a.out -a -b
optind[2] optarg[(null)] a オプションあり
a.out: option requires an argument -- b
optind[3] optarg[(null)] [?] オプション指定
$ ./a.out -a -b ccccc
optind[2] optarg[(null)] a オプションあり
optind[4] optarg[ccccc] b オプションあり
$ ./a.out -a -b ccccc -d
optind[2] optarg[(null)] a オプションあり
optind[4] optarg[ccccc] b オプションあり
a.out: illegal option -- d
optind[5] optarg[ccccc] [?] オプション指定
まぁ、便利ちゃぁ、便利で時間のないときはこれでもいいのですが。
これのロングオプション --(ハイフンを重ねる)形式を許す「getopt_long()」の方が実用性に優れています。
2. sleep
指定した時間(秒単位)、プログラムの実行を停止します。
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
非常におおざっぱな単位ですので、より正確に待ち処理を行うには、「nanosleep」を使用します。
|
|