In the context of C programming, a Command Line Interface (CLI) doesn’t inherently have prompts like an interactive shell (e.g., Bash, Zsh) or interactive programming environments (e.g., Python’s IDLE). When you execute a C program from the command line, the program runs to completion and then returns control to the shell. However, it’s possible to design a C program to act like a CLI with prompts, wait for user input, and respond to that input.
Here’s a basic example of how you might create a simple CLI prompt in a C program:
#include <stdio.h>
#include <string.h>
int main() {
char command[256];
while (1) {
printf("MyCLI> "); // Display a prompt
fgets(command, 256, stdin); // Get a line of input from the user
// Remove the newline character from the end of the command
command[strcspn(command, "\n")] = 0;
if (strcmp(command, "exit") == 0) {
break; // Exit the loop (and the program) if the user types "exit"
} else {
printf("You entered: %s\n", command); // Echo the command back to the user
}
}
return 0;
}
In this simple CLI program:
- A
while
loop is used to create a continuous prompt. - The
printf
function is used to display a prompt to the user (MyCLI>
). - The
fgets
function is used to get a line of input from the user. strcspn
andcommand[strcspn(command, "\n")] = 0;
are used to remove the newline character from the end of the command.strcmp
is used to compare the user’s input to the string"exit"
. If the user types"exit"
, the program exits. Otherwise, it echoes the command back to the user and displays the prompt again.
This is a very simplistic example, and real CLI programs are often much more complex, but this illustrates the basic idea of how a CLI prompt might be implemented in a C program.