Display the message for wrong command line string

I have the following code which calls two different function as per the command entered from the command line. My application name is minopc.exe

so when user enters the following code in command prompt

minopc.exe -regserver

srv.GBRegisterServer is called .

and when user enters the following code in command prompt

minopc.exe -unregserver

srv.GBUnRegisterServer is called .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
TCHAR *cmd_line = GetCommandLine();
TCHAR *token;
if ( (token = strchr(cmd_line, L'-')) == NULL ) token = strchr(cmd_line, L'/');
if (token)
{
   token++;
   if ( !lstrcmpi(token, LPCSTR("regserver")) || !lstrcmpi(token, LPCSTR("r")) )
   {
       srv.GBRegisterServer(&guid, L"WesOPC", L"WesOPC Server", L"WesOPC.Sample.MinOPC", L"1.0");
       return 0;
   }
  if ( !lstrcmpi(token, LPCSTR("unregserver")) || !lstrcmpi(token, LPCSTR("u")) )
  {
       srv.GBUnregisterServer(&guid);
       return 0;
  }
		
}


Now i want to display the error if the user enter other thing beside minopc.exe -regserver and minopc.exe -unregserver . But it is accepting other commands and even running the program when written like minopc.exe -a etc.

Last edited on
Do it with if / else clauses, so that it falls through and displays the error on completion.
1
2
3
4
5
6
7
8
9
10
if (token) {
    ++token;
    if (/* valid command line option */) {
        // process it
    } else if (/* valid command line option */) {
        // process it
    } else {
        // display error, and give valid usage
    }
}
Why don't you use CopmmandLineToArgvW ?
Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
LPWSTR *argv;
   int argc;

   argv = CommandLineToArgvW(GetCommandLineW(), &argc);
   if( NULL == argv )
   {
      wprintf(L"CommandLineToArgvW failed\n");
      return 0;
   }
   // process command line arguments here using argv/argc style as usual







// Free memory allocated for CommandLineToArgvW arguments.

   LocalFree(argv);


http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391%28v=vs.85%29.aspx
Last edited on
Topic archived. No new replies allowed.