5
7

More than 5 years have passed since last update.

オプション解析をしてみる

Last updated at Posted at 2014-06-28

とりあえずなにか作るとなったら基本事項のオプション解析をやってみる

C:\temp\>getopt.exe getopt.exe /n 4 /h /s /w /sw
file : getopt.exe
lines : 4
usage : 1
空 : 1
白 : 1
空白 : ふたりは
using System;
using System.IO;
using System.Collections.Generic; // Dictionary クラス使用

class MainClass
{
  static int Main(string[] args)
  {
    var opt = new Dictionary<string, string>();

    // 引数解析
    ParseArg(args, opt);
    foreach (var dict in opt)
    {
      Console.WriteLine("{0} : {1}", dict.Key, dict.Value);
    }

    return 0;
  }

  static void ParseArg(string[] args, Dictionary<string, string> opt)
  {
    //foreach (string s in args)
    for(int i=0; i<args.Length; i++)
    {
      switch(args[i])
      {
        case "/f":
          opt["follow"] = "1";
          break;
        case "/h":
          opt["usage"] = "1";
          break;
        case "/n":
          opt["lines"] = args[++i];
          break;
        default:
          if (File.Exists(args[i])) {
            opt["file"] = args[i];
          }
          break;
      }
    }
  }
}
5
7
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
5
7