1. 程式人生 > >windows下C++程式命令列引數讀取

windows下C++程式命令列引數讀取

linux下,命令列引數的讀取,可以使用系統函式getopt,還好Ludvik Jerabek實現了一個開源的getopt,我們可以直接拿來在windows程式設計中用。

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;
	}
}