0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C言語のオプション判定実装

0
Posted at

Cプログラムのオプション判定の実装

背景

C言語の勉強のため、Linuxコマンドのcatを自作しています。
catコマンドのオプションのうち、n b s E の主要オプションに絞って実装を行っています。

実装方法

getopt関数を使用します。
オプションごとにフラグを用意して、switch文でオプションのフラグを立てます。
※これは引数が必要なオプションには対応できません。

int main(int argc, char *argv[])
{
    int opt;
    int n_flag = 0;
    int b_flag = 0;
    int s_flag = 0;
    int E_flag = 0;
    
    while((opt = getopt(argc, argv, "nbsE")) != -1)
    {
        switch(opt){
            case 'n': n_flag = 1; break;
            case 'b': b_flag = 1; break;
            case 's': s_flag = 1; break;
            case 'E': E_flag = 1; break;
            case '?':
            default: return -1;
        }
    }
}

getopt関数について

プログラム起動時のargcとargv、およびオプションの文字列を引数に指定します。
argvに3つ目の引数で指定したオプションが含まれていれば、該当する文字をint型(ASCIIコード)で返してくれます。
-nオプションを指定した場合。↓

my_command -n
int main(int argc, char *argv[])
{
    int opt;
    int n_flag = 0;
    while((opt = getopt(argc, argv, "nbsE")) != -1) // optにnのASCIIコード(110)が入る。
    {
        switch(opt){
            case 'n': n_flag = 1; break; //シングルクオートで囲みASCIIコードで比較する。
    }
}

おまけ

getopt関数はargvをオプション→引数に並び変えてくれる。

オプションを引数のどこで指定しても関数内でオプションを見つけ出して、さらにargvをオプション→引数の順で並べ直してくれる。

my_command test1.txt test2.txt -n

↑のように指定した場合、argvは以下のようになるが

argv = [ my_command, test1.txt, test2.txt, -n ]

getopt関数に渡すと以下のようにargvを並び替えてくれる。

argv = [ my_command, -n, test1.txt, test2.txt ]

optind変数

おそらくargvを並び替えたあと、通常の引数が始めるインデックス番号をoptindに入れてくれる。

↓の場合は、optindは3が入る

argv = [ my_command, -n, test1.txt, test2.txt ] //optindは3

オプション以外の引数を処理す際に活用する。

for(int i = optind; i < argc; i++) // 残りの引数分for文で回す。
{
    ~
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?