I am having problems with arguments in C++ console programs built under C++Builder 12 Community Edition.
If the executable is in a folder with spaces in its name, eg. "test dir"
, and I invoke it from a console session in a DIFFERENT folder, then the arguments extracted by my code are incorrect. If the executable file path has no spaces, everything works fine. If I run it within the IDE, it's OK, too. Code built under Visual Studio 22 also works OK.
CPPtest.cpp
#include <iostream.h>
int main(int argc, char* argv[])
{
cout << "argc: " << argc << "\n";
cout << "argv0: " << argv[0] << "\n";
cout << "argv1: " << argv[1] ;
return 0 ;`
}
The executable is located in a directory named "Misc projects"
, CWD is "C:\Junk"
:
C:\Junk>C:\"Misc projects"\CPPtest 3 8
argc: 2 ## INCORRECT: Should be 3
argv0: c:\Misc projects\CPPtest.exe
argv1: projects\CPPtest 3 8 # INCORRECT should be 8
Identical code when ran inside Visual Studio 22 performs correctly.
You're quoting the file path incorrectly. Since you aren't escaping the directory separators in your path, the entire file path should be quoted, not just the portion with the space in it.
$ cd C:\Junk
$ "C:\Misc projects\CPPtest" 3 8
The program is executing, but the argument parsing's default behavior, which splits based on spaces, results in the following literal strings:
C:"Misc
projects"\CPPtest 3 8
The first quote is being inadvertently escaped by your unescaped directory separator (\"
), and no longer counts as a quote. The second quote (which is literally your first and only quote now) is unclosed, meaning everything following it is treated as a single quoted string. Therefore, the first space is causing a first split, and the remaining spaces are ignored due to the "
that isn't closed. This is one reason Windows path separators are escaped \\
.
As for the behavior differing based on execution context:
When invoking the app from the same directory as the executable, most likely the full path is being omitted when you run it, thus removing the entire escape/quote/spaces issue altogether:
# cwd is "C:\Misc projects"
$ CPPtest 3 8
# argv = ["CPPTest", "3", "8"]
When debugging through VS, the executables file path is escaped properly as part of the debug launch task, so the file path is of no consequence.
In my experience with C# CLI programming, the executable name is actually excluded entirely from the program arguments, when running in the context of the debugger.