This problem turns out to be solvable. (Though, as with most things in Windows, not 100%).
The popen
function opens a system command, which means that it is almost certainly just taking the string argument and interpolating it into cmd.exe /c <here>
.
After some interactive experimentation with cmd.exe /c
at the Windows command prompt, we hit upon a way to run a program which has spaces in its pathname.
Naive attempt with quotes, nope:
C:\>cmd /c "foo bar"
'foo' is not recognized as an internal or external command,
operable program or batch file.
Can we escape the quotes with the circumflex?
C:\>cmd /c ^"foo bar^"
'foo' is not recognized [...]
How about the space?
C:\>cmd /c foo^ bar
'foo' is not recognized [...]
How about quoting just the space?
C:\>cmd /c foo" "bar
'foo" "bar' is not recognized as an internal or external command,
operable program or batch file.
Aha! This is promising! Is it actually trying to run foo bar
? Let's see:
C:\>copy con "foo bar.bat"
echo i am foo bar
^Z
1 file(s) copied.
C:\>cmd /c foo" "bar
C:\>echo i am foo bar
i am foo bar
Aha! Our batch file with a space in its name was run!
And so, now I'm trying the following in Visual Studio 2008:
#include <stdio.h>
int main()
{
FILE *in = _popen("C:\\Program\" \"Files\\Internet\" \"Explorer\\iexplore.exe", "r");
if (in) {
char line[200];
printf("successfully opened!\n");
if (fgets(line, 200, in))
fputs(line, stdout);
_pclose(in);
}
return 0;
}
It starts Internet Explorer just fine, then blocks in the fgets
until you exit the browser (and fails to read anything since there is no output).
It does work in MinGW, which uses the Microsoft C Run-Time Library; in fact, I came up with this solution to fix a bug in the library of a programming language which is ported to Windows using MinGW.
Caveats:
This escaping trick won't escape leading spaces. It does seem to work for trailing spaces. Neither is likely a problem; we don't often see pathnames that begin or end with spaces, let alone executable path names.
I also can't find a way to escape embedded double quotes that might occur as part of a path, while at the same time handling spaces. People should probably think twice before creating something like C:\Program Files\Bob's so-called "editor"\bedit.exe
.
popen
function in MinGW (which maps to the Microsoft C Run-Time Library_popen
) which means I have to carefully encode the process name and argument strings. So, there is your answer. – Tresatrescha