In this source code example, we will see how to use the system() function in C programming with an example.
system() Function Overview
The system() function, a part of the C standard library <stdlib.h>, allows you to execute system commands or shell commands directly from a C program. It can be used to interact with the operating system, run other programs, or perform various system operations.
Source Code Example
#include <stdio.h>
#include <stdlib.h>
int main() {
// Basic usage: Listing files in the current directory
printf("Listing files in the current directory:\n");
system("ls"); // Use "dir" on Windows systems
// Using system() to clear the console screen
// system("clear"); // For Linux/MacOS. Uncomment to use.
// system("cls"); // For Windows. Uncomment to use.
// Running another program using system()
printf("\nDisplaying the current date and time:\n");
system("date");
// Creating a new directory
printf("\nCreating a new directory named 'exampleDir':\n");
system("mkdir exampleDir");
return 0;
}
Output
(The exact output might differ based on the system and the directory content.) Listing files in the current directory: file1.txt file2.c myprogram Displaying the current date and time: Thu Mar 10 14:33:07 UTC 2023 Creating a new directory named 'exampleDir':
Explanation
1. We first use the system() function to list all files in the current directory. Note that the command might differ based on your operating system.
2. You can clear the console screen using system commands. Commands vary based on the operating system: 'clear' for Linux/MacOS and 'cls' for Windows.
3. To display the current date and time, we use the date command via the system() function.
4. Lastly, we demonstrate how you can create a new directory using the system() function. Caution: Be careful when using the system() function, as executing arbitrary or user-provided commands can expose security risks. Ensure that your code does not allow for unintended or malicious command execution.
Comments
Post a Comment