2009年7月16日 星期四

parse command line in Win32 API

#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <stdlib.h>

// 出處:http://www.codeguru.com/cpp/w-p/win32/comments.php/c1427/?thread=3545
// A Simple Win32 Command-Line Parser

#include <windows.h>

char **argv = NULL;

/*******************************************************
WIN32 command line parser function
********************************************************/
int ParseCommandline()
{
 int    argc, BuffSize, i;
 WCHAR  *wcCommandLine;
 LPWSTR *argw;

 // Get a WCHAR version of the parsed commande line
 wcCommandLine = GetCommandLineW(); 
 argw = CommandLineToArgvW( wcCommandLine, &argc);

 // Create the first dimension of the double array
 argv = (char **)GlobalAlloc( LPTR, argc + 1 );

 // convert eich line of wcCommandeLine to MultiByte and place them
 // to the argv[] array
 for( i=0; i<argc; i++)
 {
  BuffSize = WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, argw[i], -1, NULL, 0, NULL, NULL );
  argv[i] = (char *)GlobalAlloc( LPTR, BuffSize );  
  WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, argw[i], BuffSize * sizeof( WCHAR ) ,argv[i], BuffSize, NULL, NULL );
 }

 // return the number of argument
 return argc;
}

//Command Line argument parsing 
//linux: getopt
//windows ?
int main( int argc, char **argv ) {
 argc = ParseCommandline();
 for(int i=0; i<argc; i++){
  printf("%s\n", argv[i]);
 }
 system("pause");
 return 0;
} 

0 意見: