copendir
并不是标准的 C 或 POSIX 函数,你可能指的是 opendir
函数。在 C 语言中,我们使用 opendir
、readdir
和 closedir
来遍历目录。下面是一个完整的示例:
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
if (argc < 2) {
printf("Usage: %s directory_name\n", argv[0]);
return 1;
}
// 打开目录
if ((dir = opendir(argv[1])) == NULL) {
perror("opendir");
return 1;
}
printf("Contents of directory '%s':\n", argv[1]);
// 读取目录内容
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
// 关闭目录
closedir(dir);
return 0;
}
如果需要递归遍历所有子目录,可以使用以下代码:
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
void listFiles(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char fullpath[PATH_MAX];
if ((dir = opendir(path)) == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
// 跳过 "." 和 ".."
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// 构建完整路径
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
// 获取文件信息
if (lstat(fullpath, &statbuf) == -1) {
perror("lstat");
continue;
}
printf("%s\n", fullpath);
// 如果是目录,递归调用
if (S_ISDIR(statbuf.st_mode)) {
listFiles(fullpath);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s directory_name\n", argv[0]);
return 1;
}
listFiles(argv[1]);
return 0;
}
lstat
而不是 stat
来正确处理符号链接如果你确实需要 Windows 版本的目录遍历代码,或者有其他特定需求,请告诉我,我可以提供相应的解决方案。