Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting argv back to a single string

I'm writing a (Win32 Console) program that wraps another process; it takes parameters as in the following example:

runas.exe user notepad foo.txt

That is: runas parses user and then will run notepad, passing the remaining parameters.

My problem is that argv is broken down into individual parameters, but CreateProcessAsUser requires a single lpszCommandLine parameter.

Building this command line is probably not as simple as just joining argv back together with spaces. Any pointers?

This is just an example. My first argument isn't actually a user name, and might have spaces in it. This makes manually parsing the result of GetCommandLine tricky.

Similarly, a naive concatenation of argv won't work, because it needs to deal with the case where the original arguments were quoted and might have spaces in them.

like image 276
Roger Lipscombe Avatar asked Jun 10 '09 11:06

Roger Lipscombe


3 Answers

Manually recombining them is hard:

You could try to re-combine them, I think it would work, but be sure to following the same command line escaping rules that windows has. This could be more than the trivial solution you're looking for.

Also if there are any parameters that have spaces in them, then you would want to join them to the string with quotes around them. Here is an example of a strange escaping rule: if you have --folderpath "c:\test\" then the last backslash has to be doubled --folderpath "c:\test\\".

If you are using MFC:

You can can get the value you want from your derived CWinApp's theApp.m_lpCmdLine. Note you could still access them the other way too with __argc, and __argv or CommandLineToArgvW.

If you are using Win32 only (even without a GUI):

You can get it from WinMain. Which can be your program's entry point.

Note you could still access them the other way too with __argc, and __argv or CommandLineToArgvW.

If you must use a console based application with main or wmain:

The Win32 API GetCommandLine seems to be the way to go. You would need to still parse this to get past the .exe name though. Take into account quotes around the exe name/path too. If there are no such quotes at the start, then just go to the next space for the start.

like image 123
Brian R. Bondy Avatar answered Sep 30 '22 09:09

Brian R. Bondy


You can use the GetCommandLine function.

Why not use 'WinMain' instead of 'main'? This should give you the string in the format you want.

like image 41
Agnel Kurian Avatar answered Sep 30 '22 11:09

Agnel Kurian


There is Win32 API call that returns command line: GetCommandLine

like image 40
David Elkind Avatar answered Sep 30 '22 09:09

David Elkind