在 Ubuntu(Linux)下,如果你使用了 opendir() 打开目录,关闭目录要用 closedir(),而不是 close()。
#include <dirent.h>
DIR *dir = opendir("/some/path");
if (dir == NULL) {
perror("opendir");
return -1;
}
// 使用 readdir() 读取目录...
closedir(dir); // 关闭目录
不要混用 close()
close(dir); // ❌ 错误,dir 是 DIR* 不是 int fd
opendir() 返回的是 DIR *,对应的关闭函数是 closedir()。
必须检查返回值
if (closedir(dir) == -1) {
perror("closedir");
}
用完一定要关
不调用 closedir() 会造成文件描述符泄漏,特别是在循环或长时间运行的程序中。
open() 打开目录(不推荐)如果你用的是:
int fd = open("/path", O_RDONLY | O_DIRECTORY);
那才用:
close(fd);
如果你能贴一下你的代码片段,我可以具体帮你看哪里没关对。