Monday, May 16, 2011

Executing system commands

In stdlib.h (or cstdlib in C++), you can find the system() function, which you can use to execute system commands as though you were typing in a command at the command prompt. The function take a char * as a parameter, and you can specify your system command as either a string literal

system("Prgrm Prmtr1 Prmtr2")

or as a pointer to a null-terminated string

system(cmd_pointer)

The use of system is often advised against if there is another solution. The reason for this is that you do not always know if the program you are calling exists. For example, if you type

system("notepad")

your program will not work properly if Notepad has been deleted, or if you are using an operating system other than Windows.

The use of system is not 'forbidden', but keep this in mind when programming, and try, whenever practical, to use a more portable and safe solution.