Hello, System

One thing that continues to puzzle me about learning the C language is how frequently beginners use the system() function. Is it a crutch? Is it a necessity? What’s the allure of this function that makes it show up in beginner code?

The system() function is an old and necessary function. It spawns a new shell and sends a command to that shell. The whole effect is that you can run one program from within another. In fact, the terminal window uses the system() function to run other programs. Even graphical operating systems use system() (or some variation) to launch programs and apps.

As an example, suppose your code needs run the blorf program. If so, you’d use the following statement:

    system("blorf");

At that point in the code, your program snoozes and program blorf starts. When blorf terminates, control returns back to your code.

Beginning C programmers typically use the system() function to clear the screen. All too often, I’d see the following example either written by a beginner or presented as an example in some oddball C programming text:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Press any key to clear the screen:");
    getchar();
    system("cls");    /* use "clear" for Unix */
    printf("Thanks!\n");

    return(0);
}

The system() function is prototyped in the stdlib.h header file. Beyond that, its argument is a command line string, something you’d type at the prompt, such as cls (DOS) or clear (Unix).

C is stream-oriented, so clearing the screen isn’t something offered by the C library; to clear the screen you must either program the terminal directly or use a screen manipulation library, such as NCurses. The other way you can clear the screen is to call the terminal (or operating system in the case of DOS) and issue the clear-screen command.

I’ve used the system() function to write a DOS menu system, as well as in some of my programs so that the user could “shell to DOS.” Next week, I’ll provide a practical example of how to use the system() function, one that I frequently use when testing my code.

Leave a Reply