用C语言写一个类似于DOS命令的伪系统命令程序,并且要有打开程序的功能
时间: 2023-02-12 18:37:45 浏览: 67
好的,我来为你写一个类似于 DOS 命令的伪系统命令程序。
首先,我们要包含必要的头文件:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
```
然后我们可以定义一个结构体来保存系统命令的信息:
```
struct command {
char *name;
char *desc;
void (*func)(int, char **);
};
```
其中,`name` 字段表示命令的名称,`desc` 字段表示命令的描述,`func` 字段表示命令对应的函数。
接下来我们可以定义一些系统命令,并将它们放到一个数组中:
```
struct command commands[] = {
{"help", "show the help message", cmd_help},
{"cd", "change the current directory", cmd_cd},
{"exit", "exit the program", cmd_exit},
{"open", "open a program or file", cmd_open},
};
```
其中,`cmd_help`、`cmd_cd`、`cmd_exit` 和 `cmd_open` 分别是对应的命令函数。
接下来是命令函数的实现:
```
void cmd_help(int argc, char **argv) {
printf("available commands:\n");
for (int i = 0; i < sizeof(commands) / sizeof(struct command); i++) {
printf(" %s\t%s\n", commands[i].name, commands[i].desc);
}
}
void cmd_cd(int argc, char **argv) {
if (argc != 2) {
printf("usage: cd <directory>\n");
return;
}
if (chdir(argv[1]) != 0) {
perror("error");
}
}
void cmd_exit(int argc, char **argv) {
exit(0);
}
void cmd_open(int argc, char **argv) {
if (argc != 2) {
printf("usage: open <program or file>\n");
return;
}
if (system(argv