• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
sn-genuine
博客园    首页    新随笔    联系   管理    订阅  订阅

Linux 目录操作 C/C++ 笔记

Linux 目录操作 C/C++ 开发笔记


一、目录操作基础头文件汇总

功能 头文件
目录遍历(opendir/readdir/closedir) <dirent.h>
创建目录(mkdir) <sys/stat.h>
删除/切换目录、获取当前目录 <unistd.h>

二、常用目录操作函数详解

1. 获取当前工作目录:getcwd()

1.1 函数原型

#include <unistd.h>
char *getcwd(char *buf, size_t size);
  • buf:存放当前目录路径的缓冲区(建议长度 256)
  • size:缓冲区大小
  • 返回值:成功返回 buf 地址,失败返回 NULL

1.2 示例代码

#include <iostream>
#include <unistd.h>
using namespace std;

int main() {
    char path[256];
    if (getcwd(path, sizeof(path)) == NULL) {
        perror("getcwd");
        return -1;
    }
    cout << "当前工作目录:" << path << endl;
    return 0;
}

2. 切换工作目录:chdir()

2.1 函数原型

#include <unistd.h>
int chdir(const char *path);
  • path:目标目录路径
  • 返回值:成功返回 0,失败返回 -1

2.2 示例代码

#include <iostream>
#include <unistd.h>
using namespace std;

int main() {
    if (chdir("/home/user") == -1) {
        perror("chdir");
        return -1;
    }
    char path[256];
    getcwd(path, sizeof(path));
    cout << "切换后目录:" << path << endl;
    return 0;
}

3. 创建目录:mkdir()

3.1 函数原型

#include <sys/stat.h>
int mkdir(const char *pathname, mode_t mode);
  • pathname:要创建的目录路径
  • mode:权限(如 0755,注意必须带前导 0,因为是八进制数)
  • 返回值:成功返回 0,失败返回 -1

3.2 示例代码

#include <iostream>
#include <sys/stat.h>
using namespace std;

int main() {
    if (mkdir("./new_dir", 0755) == -1) {
        perror("mkdir");
        return -1;
    }
    cout << "目录创建成功" << endl;
    return 0;
}

4. 删除目录:rmdir()

4.1 函数原型

#include <unistd.h>
int rmdir(const char *path);
  • path:要删除的目录路径(必须为空目录)
  • 返回值:成功返回 0,失败返回 -1

4.2 示例代码

#include <iostream>
#include <unistd.h>
using namespace std;

int main() {
    if (rmdir("./new_dir") == -1) {
        perror("rmdir");
        return -1;
    }
    cout << "目录删除成功" << endl;
    return 0;
}

三、目录遍历核心函数(opendir/readdir/closedir)

1. 核心数据结构

1.1 目录指针 DIR

  • 类型:DIR *
  • 作用:表示一个打开的目录流

1.2 目录项结构体 struct dirent

struct dirent {
    long d_ino;              // inode 号
    off_t d_off;             // 在目录文件中的偏移
    unsigned short d_reclen; // 记录长度
    unsigned char d_type;    // 文件类型(重点)
    char d_name[256];        // 文件名(重点)
};

1.3 d_type 常用值

宏 含义 数值(部分系统)
DT_REG 普通文件 8
DT_DIR 目录 4
DT_LNK 符号链接 10
DT_FIFO 管道 1

2. 目录遍历三步骤

2.1 打开目录:opendir()

#include <dirent.h>
DIR *opendir(const char *pathname);
  • 返回值:成功返回目录流指针,失败返回 NULL

2.2 读取目录项:readdir()

struct dirent *readdir(DIR *dirp);
  • 每次调用返回下一个目录项,读完返回 NULL

2.3 关闭目录:closedir()

int closedir(DIR *dirp);
  • 成功返回 0,失败返回 -1

3. 完整示例代码

#include <iostream>
#include <dirent.h>
#include <cstring>
using namespace std;

int main(int argc, char *argv[]) {
    if (argc != 2) {
        cout << "Usage: " << argv[0] << " <目录名>\n";
        return -1;
    }

    // 1. 打开目录
    DIR *dir = opendir(argv[1]);
    if (dir == nullptr) {
        perror("opendir");
        return -1;
    }

    // 2. 遍历目录项
    struct dirent *entry;
    while ((entry = readdir(dir)) != nullptr) {
        // 跳过 . 和 .. 目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        cout << "文件名:" << entry->d_name << "\t类型:";
        switch (entry->d_type) {
            case DT_REG: cout << "普通文件"; break;
            case DT_DIR: cout << "目录"; break;
            case DT_LNK: cout << "符号链接"; break;
            default: cout << "其他(" << (int)entry->d_type << ")"; break;
        }
        cout << endl;
    }

    // 3. 关闭目录
    closedir(dir);
    return 0;
}

四、知识点补充与易错点修正

1. rmdir() 只能删除空目录

  • 如果目录非空,必须先删除所有文件和子目录,再调用 rmdir()

2. mkdir() 权限问题

  • 权限模式必须是八进制,如 0755,不能写成 755
  • 权限受进程的 umask 影响,实际权限为 mode & ~umask

3. readdir() 会自动跳过 . 和 .. 吗?

  • 不会,必须手动判断并跳过,否则会遍历到这两个特殊目录

4. 目录操作错误排查

  • 始终用 perror() 打印错误信息,如 perror("opendir")
  • 常见错误:路径不存在、权限不足、目录非空

五、目录操作流程总结

  1. 获取/切换目录:getcwd()/chdir()
  2. 创建/删除目录:mkdir()/rmdir()
  3. 遍历目录:opendir() → readdir() 循环 → closedir()
posted on 2026-05-06 14:55  SobNov  阅读(10)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3