在Linux下实现一个简单的ls命令的C语言程序,可以使用dirent.h库来读取目录内容,并使用stat.h库来获取文件的详细信息。以下是一个简单的实现:
#include
#include
#include
#include <sys/stat.h>
#include
#include
#include
void print_file_info(const char *path, const char *filename) {
struct stat file_stat;
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, filename);
if (stat(full_path, &file_stat) < 0 perrorstat return printfs_isdirfile_stat.st_mode d : - printffile_stat.st_mode s_irusr r : - printffile_stat.st_mode s_iwusr w : - printffile_stat.st_mode s_ixusr x : - printffile_stat.st_mode s_irgrp r : - printffile_stat.st_mode s_iwgrp w : - printffile_stat.st_mode s_ixgrp x : - printffile_stat.st_mode s_iroth r : - printffile_stat.st_mode s_iwoth w : - printffile_stat.st_mode s_ixoth x : - printf ld file_stat.st_nlink struct passwd pwd='getpwuid(file_stat.st_uid);' printf s pwd pwd->pw_name : "unknown");
// 所属组
struct group *grp = getgrgid(file_stat.st_gid);
printf(" %s", grp ? grp->gr_name : "unknown");
// 文件大小
printf(" %ld", file_stat.st_size);
// 最后修改时间
char time_buf[80];
strftime(time_buf, sizeof(time_buf), "%b %d %H:%M", localtime(&file_stat.st_mtime));
printf(" %s", time_buf);
// 文件名
printf(" %s\n", filename);
}
void list_directory(const char *path) {
DIR *dir;
struct dirent *entry;
if ((dir = opendir(path)) == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') {
continue; // 跳过隐藏文件
}
print_file_info(path, entry->d_name);
}
closedir(dir);
}
int main(int argc, char *argv[]) {
const char *path = argc > 1 ? argv[1] : ".";
list_directory(path);
return 0;
}
代码说明:
- print_file_info 函数:用于打印文件的详细信息,包括文件类型、权限、硬链接数、所有者、所属组、文件大小和最后修改时间。
- list_directory 函数:用于列出指定目录下的所有文件(不包括隐藏文件)。
- main 函数:解析命令行参数,如果没有指定目录,则默认列出当前目录的内容。
编译和运行:
- 将上述代码保存为 myls.c。
- 使用以下命令编译:
gcc myls.c -o myls
- 运行生成的可执行文件:
./myls /path/to/directory
- 如果不指定目录,默认会列出当前目录的内容。
注意:
- 这个实现是一个简化版的 ls 命令,不支持 ls 的所有选项(如 -l, -a, -R 等)。
- 如果需要实现更复杂的功能(如递归列出子目录、支持更多选项等),可以在此基础上进行扩展。
这个程序展示了如何使用C语言在Linux下读取目录内容并打印文件信息,类似于 ls 命令的基本功能。