C programming stdlib.h function - int system(const char *string)

www.igift‮i‬dea.com

The system function is a standard library function in C that is used to execute a command as if it were typed at the command line. The system function takes a single argument, which is a pointer to a null-terminated string containing the command to execute.

The syntax of the system function is as follows:

int system(const char *string);

The system function executes the command specified by the string argument, by passing it to the command interpreter (typically a shell). The function returns an implementation-defined value that indicates the success or failure of the command.

Here is an example that demonstrates how to use the system function:

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

int main(void) {
    int status = system("ls -l");
    if (status == -1) {
        printf("Command execution failed.\n");
    } else {
        printf("Command exited with status %d.\n", status);
    }
    return 0;
}

In this example, the system function is used to execute the ls -l command, which lists the files in the current directory with detailed information. The return value of the system function is stored in the status variable, and then printed to the console using printf.

Note that the system function is not a secure way to execute commands, because it can be vulnerable to command injection attacks. It is recommended to use more secure methods, such as the exec family of functions, when executing commands that involve user input.