温馨提示×

ubuntu copendir如何关闭

小樊
51
2026-10-02 16:50:59
栏目: 智能运维

在 Ubuntu(Linux)下,如果你使用了 opendir() 打开目录,关闭目录要用 closedir(),而不是 close()。

基本用法

#include <dirent.h>

DIR *dir = opendir("/some/path");
if (dir == NULL) {
    perror("opendir");
    return -1;
}

// 使用 readdir() 读取目录...

closedir(dir);  // 关闭目录

注意事项

  1. 不要混用 close()

    close(dir);  // ❌ 错误,dir 是 DIR* 不是 int fd
    

    opendir() 返回的是 DIR *,对应的关闭函数是 closedir()。

  2. 必须检查返回值

    if (closedir(dir) == -1) {
        perror("closedir");
    }
    
  3. 用完一定要关 不调用 closedir() 会造成文件描述符泄漏,特别是在循环或长时间运行的程序中。

如果你是用 open() 打开目录(不推荐)

如果你用的是:

int fd = open("/path", O_RDONLY | O_DIRECTORY);

那才用:

close(fd);

如果你能贴一下你的代码片段,我可以具体帮你看哪里没关对。

0 踩