The system() command works by spawning the command shell. On Windows, this is
cmd.exe (or whatever %COMSPEC% indicates, presumably. Read your compiler's documentation).
Hence, you must use the Windows methods of quoting stuff. Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
/* a.c
* Demonstrates using system() on Windows.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
if (0 != system( "\"C:\\Program Files\\Windows NT\\Accessories\\"
"wordpad.exe\" a.c >nul 2>&1" ))
{
fprintf( stderr, "Failure to execute MS WordPad.\n" );
return 1;
}
puts( "Success!" );
return 0;
}
| |
A few notes:
1. Notice how the entire pathname was surrounded in double-quotes. Also notice how I had to escape them using the
\" string-literal sequence.
2. As
Mythios said for
\\ .
3. Remember that in C you can break your string literals across multiple lines. The compiler will concatenate them for you. Hence, it is only
one string being passed to the system() function there. (I suppose I didn't really need to do this here, but then I figured, why not? Might as well slip something interesting in there.)
4. Both standard output and standard error are redirected to the DOS
nul device. (On *nix you would redirect to
/dev/null .) This prevents the spawned
cmd.exe shell from printing unwanted error messages on your terminal.
5. The system() command is a
blocking command. It only returns when the spawned command shell terminates. The return code is zero if the shell was able to successfully execute the desired command, and non-zero on failure. This is only a very general guideline --it is entirely possible to get the command shell to think everything went fine even if something went wrong.
If you want just to start another process
without waiting for it to terminate, use the
start command:
1 2
|
/* Print a little wizard */
system( "start mspaint.exe /p C:\\WINDOWS\\system32\\oobe\\images\\merlin.gif" );
| |
You cannot stop GUI's from popping-up messages (you can a few, if you know what you are doing, but in general it isn't worth the effort with system()), and that is the case with
start. If it cannot find the program to execute it will display an error dialog, wait for the user to press OK, then return failure to your program.
Well, that should do it. If you wish to do anything more complex than above, then the system() function is not adequate; use a system-dependant function instead. On Windows, that is one of ShellExecute() or CreateProcess().
Hope this helps.