linux下,命令行参数的读取,可以使用系统函数getopt,还好Ludvik Jerabek实现了一个开源的getopt,我们可以直接拿来在windows编程中用。
到http://www.codeproject.com/Articles/157001/Full-getopt-Port-for-Unicode-and-Multibyte-Microso下载需要的版本,解压后将头文件和源文件直接引入到工程中,在vs环境中,定义如下的预处理器:
STATIC_GETOPT
然后就可以体会getopt带来的便利了:
bool isHelp = false;
bool isDownload = false;
bool isUpload = false;
string url;
string filePath;
string loginUrl;
string getFields = "";
string postFields = "";
static struct option long_options[] =
{
{ _T("help"), ARG_NONE, 0, _T('h') },
{ _T("download"), ARG_NONE, 0, _T('d') },
{ _T("upload"), ARG_NONE, 0, _T('u') },
{ _T("url"), ARG_REQ, 0, _T('r') },
{ _T("file_path"), ARG_REQ, 0, _T('f') },
{ _T("login_url"), ARG_REQ, 0, _T('l') },
{ _T("post_fields"), ARG_REQ, 0, _T('p') },
{ _T("get_fields"), ARG_REQ, 0, _T('g') },
{ ARG_NULL, ARG_NULL, ARG_NULL, ARG_NULL }
};
int option_index = 0;
int ch;
while ((ch = getopt_long(argc, argv, _T("hdur:f:c:l:g:p:"), long_options, &option_index)) != -1) {
switch (ch) {
case _T('h'): isHelp = true; break;
case _T('d'): isDownload = true; break;
case _T('u'): isUpload = true; break;
case _T('r'): Wchar_tToString(url, optarg); break;
case _T('f'): Wchar_tToString(filePath, optarg); break;
case _T('l'): Wchar_tToString(loginUrl, optarg); break;
case _T('g'): Wchar_tToString(getFields, optarg); break;
case _T('p'): Wchar_tToString(postFields, optarg); break;
}
}