写一个Linux c语言函数,对于指定路径是文件时,打印文件名,是目录时,打印目录下所有文件文件名
时间: 2024-03-20 17:42:54 浏览: 18
可以使用 `stat()` 函数判断指定路径是文件还是目录,如果是文件,则直接打印文件名;如果是目录,则需要递归遍历目录下的所有文件,并逐一打印文件名。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
void list_files(const char *path) {
struct stat sb;
DIR *dir;
struct dirent *entry;
if (stat(path, &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
if (S_ISREG(sb.st_mode)) { // 如果是普通文件
printf("%s\n", path);
} else if (S_ISDIR(sb.st_mode)) { // 如果是目录
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue; // 忽略 "." 和 ".." 目录
}
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
list_files(full_path); // 递归遍历子目录
}
closedir(dir);
}
}
```
在该函数中,首先通过 `stat()` 函数获取指定路径的文件信息,然后根据文件类型进行判断,如果是普通文件,则直接输出文件名;如果是目录,则打开目录并递归遍历子文件。需要注意的是,这里忽略了 `.` 和 `..` 目录,避免出现死循环。