Debian 下 copendir 出错的定位与修复
一、先确认函数与常见原因
二、快速排查步骤
三、最小可复现示例与正确用法
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "用法: %s <目录路径>\n", argv[0]);
return EXIT_FAILURE;
}
const char *path = argv[1];
DIR *dir = opendir(path);
if (dir == NULL) {
// 同时输出函数名与系统错误信息,便于定位
fprintf(stderr, "opendir 失败: %s: %s\n", path, strerror(errno));
return EXIT_FAILURE;
}
// 示例:遍历并打印条目名
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过 "." 和 ".."
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;
printf("%s\n", entry->d_name);
}
if (closedir(dir) == -1) {
fprintf(stderr, "closedir 失败: %s: %s\n", path, strerror(errno));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
四、若实际要做“复制目录”
五、性能与稳定性建议