编写一个用户程序的源代码文件,实现目录列表、改变目录和删除文件等基本功能
时间: 2024-02-05 15:02:43 浏览: 22
好的,这里给您提供一个简单的Shell程序示例,实现了目录列表、改变目录和删除文件等基本功能。该程序使用C语言编写,可以在Linux系统下编译和运行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
// 显示当前目录下的文件和目录列表
void list_dir() {
DIR *dir;
struct dirent *dir_ent;
struct stat file_stat;
// 打开当前目录
if ((dir = opendir(".")) == NULL) {
perror("opendir error");
exit(EXIT_FAILURE);
}
// 遍历当前目录下的文件和目录
while ((dir_ent = readdir(dir)) != NULL) {
// 获取文件或目录的属性信息
if (stat(dir_ent->d_name, &file_stat) == -1) {
perror("stat error");
exit(EXIT_FAILURE);
}
// 根据属性信息判断是文件还是目录,并打印名称
if (S_ISREG(file_stat.st_mode)) {
printf("%s\n", dir_ent->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("%s/\n", dir_ent->d_name);
}
}
// 关闭目录
closedir(dir);
}
// 改变当前工作目录
void change_dir(char *path) {
if (chdir(path) == -1) {
perror("chdir error");
exit(EXIT_FAILURE);
}
}
// 删除指定文件
void delete_file(char *path) {
if (unlink(path) == -1) {
perror("unlink error");
exit(EXIT_FAILURE);
}
}
int main() {
char cmd[1024];
char path[1024];
// 循环读取用户输入的命令
while (1) {
printf("> ");
fgets(cmd, sizeof(cmd), stdin);
// 去掉命令字符串中的换行符
cmd[strcspn(cmd, "\n")] = 0;
// 解析命令,并执行相应操作
if (strcmp(cmd, "ls") == 0) {
list_dir();
} else if (strncmp(cmd, "cd ", 3) == 0) {
sscanf(cmd + 3, "%s", path);
change_dir(path);
} else if (strncmp(cmd, "rm ", 3) == 0) {
sscanf(cmd + 3, "%s", path);
delete_file(path);
} else if (strcmp(cmd, "exit") == 0) {
break;
} else {
printf("Unknown command: %s\n", cmd);
}
}
return 0;
}
```
您可以将该代码保存为一个名为`shell.c`的文件,并使用以下命令进行编译和运行:
```
gcc -o shell shell.c
./shell
```
当程序运行后,您可以输入`ls`来列出当前目录下的文件和目录,输入`cd /path/to/dir`来改变当前工作目录,输入`rm /path/to/file`来删除指定文件。程序支持的命令不仅限于这些,您可以按照需要进行扩展。