C standard library provides functions system
and popen
to run a command. But is there a portable way to detect if a command exists?
views:
203answers:
2
+3
A:
No, there isn't any standard C function for that.
The Unix-only solution is to split getenv("PATH")
on :
(colon), and try to find the command executable (with the stat
function) in the directories.
pts
2009-05-21 00:30:25
+1. On Windows, it's a bit different: break on ";" not ":", and you need to check files ending with (at least) ".exe", ".com" and ".bat". In fact it's trickier than that -- as I recall, cmd.exe searches for .com files first in ALL directories, then for .exe files in ALL directories, etc. I don't recall the details unfortunately, but it *is* different than the order used by CreateProcess().
j_random_hacker
2009-05-21 05:02:23
On Windows, there are many more executable extensions, such as .pif, .lnk, .vbs, .scr etc. It would be better to find an API call to list all of them instead of hardcoding them.
pts
2009-05-21 09:06:37
+2
A:
While I don't think there is a completely portable way to do this (some systems don't even support command interpreters), system()
does return 0 if there were no errors while running your command. I suppose you could just try running your command and then check the return value of system.
To check if a command interpreter is available, call system( NULL )
and check for a non-zero value.
Naaff
2009-05-21 01:04:18