Communicating with the OS using system
What you'll learn: How to use the system() function to execute external commands directly from your C program.
The Messenger to the Shell
Think of your C program as a manager working inside a private office. Most of the time, the manager handles internal tasks—calculating numbers or moving data around. However, sometimes the manager needs something from the outside world, like creating a new folder on the hard drive or checking the current network status. Instead of doing this manually, the manager opens a window and shouts a command to an assistant standing outside in the "System Shell."
In C, the system() function, found in the <stdlib.h> library, is that window. It allows you to send a string of text to your operating system’s command processor (like Command Prompt on Windows or Terminal on Linux/macOS) as if you had typed it there yourself.
How to use it
The function takes a single argument: a string containing the command you want to run. When the line is executed, your C program pauses, the operating system runs the command, and your program resumes once the command finishes.
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Checking the files in the current directory...\n");
// On Windows, use "dir". On Linux/macOS, use "ls".
// This executes the command just like in a terminal.
int result = system("ls");
if (result == -1) {
printf("The command failed to run.\n");
} else {
printf("\nCommand executed successfully.\n");
}
return 0;
}
The Trade-off
While system() is incredibly powerful because it gives you access to every tool your OS possesses, it comes with a warning. First, it is "platform dependent"—a program using system("dir") will crash or fail on a Mac, which expects ls.
Second, it is a security risk if you allow user input to be part of the command string. If a user types a command to delete your hard drive instead of a filename, system() will obediently carry it out. Use it for simple, hard-coded tasks, but reach for specialized C functions for more complex operations.
Key takeaway
The system() function is a quick way to run terminal commands from your code, acting as a bridge between your program and the operating system.