用c语言编写一个简单的,支持cd,clr,dir,environ,help,pause,quit的内部指令
时间: 2023-05-21 17:02:35 浏览: 194
以下是一个简单的C语言程序,支持cd,clr,dir,environ,help,pause,quit的内部指令:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/wait.h>
void cd(char *path) {
if (chdir(path) == -1) {
printf("cd: %s: No such file or directory\n", path);
}
}
void clr() {
printf("\033[2J\033[1;1H");
}
void dir() {
DIR *dir;
struct dirent *entry;
if ((dir = opendir(".")) == NULL) {
printf("dir: cannot open directory\n");
return;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
}
void environ() {
extern char **environ;
char **env = environ;
while (*env) {
printf("%s\n", *env++);
}
}
void help() {
printf("cd <path> Change the current working directory\n");
printf("clr Clear the screen\n");
printf("dir List the contents of the current directory\n");
printf("environ List all environment variables\n");
printf("help Display this help message\n");
printf("pause Pause the program until Enter is pressed\n");
printf("quit Exit the program\n");
}
void pause_cmd() {
printf("Press Enter to continue...");
getchar();
}
int main() {
char input[256];
char *args[64];
int status;
pid_t pid;
while (1) {
printf("> ");
fgets(input, 256, stdin);
input[strlen(input) - 1] = '\0';
int i = 0;
args[i] = strtok(input, " ");
while (args[i] != NULL) {
i++;
args[i] = strtok(NULL, " ");
}
if (strcmp(args[0], "cd") == 0) {
cd(args[1]);
} else if (strcmp(args[0], "clr") == 0) {
clr();
} else if (strcmp(args[0], "dir") == 0) {
dir();
} else if (strcmp(args[0], "environ") == 0) {
environ();
} else if (strcmp(args[0], "help") == 0) {
help();
} else if (strcmp(args[0], "pause") == 0) {
pause_cmd();
} else if (strcmp(args[0], "quit") == 0) {
break;
} else {
pid = fork();
if (pid == 0) {
execvp(args[0], args);
printf("Unknown command: %s\n", args[0]);
exit(1);
} else {
wait(&status);
}
}
}
return 0;
}
阅读全文