C/C++ 对文件目录进行操作的常用函数

在C语言中,对目录进行操作的常用函数主要包括但不限于以下几个:

  1. opendir(const char *name):
    • 功能:打开指定路径的目录。
    • 返回值:成功时返回一个指向DIR结构体的指针,失败则返回NULL
    • 头文件<dirent.h>
  2. readdir(DIR *dirp):
    • 功能:从打开的目录中读取下一个目录条目。
    • 返回值:成功时返回一个指向dirent结构体的指针,代表当前条目;当没有更多条目时返回NULL
    • 头文件<dirent.h>
  3. closedir(DIR *dirp):
    • 功能:关闭由opendir打开的目录。
    • 返回值:成功时返回0,失败返回-1。
    • 头文件<dirent.h>
  4. mkdir(const char *pathname, mode_t mode):
    • 功能:创建一个新的目录。
    • 参数pathname是新目录的路径名,mode指定目录的权限位。
    • 返回值:成功时返回0,失败返回-1。
    • 头文件<sys/stat.h><sys/types.h><unistd.h>
  5. rmdir(const char *pathname):
    • 功能:删除一个空目录。
    • 返回值:成功时返回0,失败返回-1。
    • 头文件<unistd.h>
  6. chdir(const char *path):
    • 功能:更改当前工作目录到指定的路径。
    • 返回值:成功时返回0,失败返回-1。
    • 头文件<unistd.h>
  7. getcwd(char *buf, size_t size):
    • 功能:获取当前工作目录的路径并存入缓冲区buf中。
    • 返回值:成功时返回指向缓冲区的指针,失败返回NULL
    • 头文件<unistd.h>
  8. stat(const char *path, struct stat *buf):
    • 功能:获取指定文件或目录的状态信息(如大小、修改时间、权限等)。
    • 返回值:成功时返回0,失败返回-1。
    • 头文件<sys/stat.h>

这些函数构成了在C语言中进行目录操作的基础工具集,可以用于遍历目录、创建/删除目录、改变当前目录以及获取目录或文件的元数据信息等操作。

相关代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>   //定义了用于遍历目录结构的类型和函数
#include <sys/stat.h> //提供了用于获取文件或目录状态信息的接口

int listFile(char *dirPath)
{
    DIR *dir = opendir(dirPath);
    struct stat file_stat;
    char fullPath[PATH_MAX];
    struct dirent *entry;

    // 打开指定路径的目录
    if (!dir)
    {
        perror("opendir failed\n");
        return -1;
    }

    while ((entry = readdir(dir)) != NULL)
    {
        // 跳过当前自身目录"."和".."父目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
        {
            continue;
        }

        // 构建完整路径
        snprintf(fullPath, PATH_MAX, "%s/%s", dirPath, entry->d_name);

        // 获取文件状态信息
        if (stat(fullPath, &file_stat) == -1)
        {
            perror("failed to get stats for file\n");
            continue;
        }

        // 打印文件名和大小
        printf("%-20s %ld bytes\n", entry->d_name, (long)file_stat.st_size);
    }

    // 关闭目录
    closedir(dir);

    return 0;
}

int main()
{
    char dir_path[PATH_MAX]; // 使用字符数组存储目录路径

    printf("请输入目录地址: ");
    fgets(dir_path, PATH_MAX, stdin); // 使用fgets读取输入,包括空格

    // 移除fgets读取的末尾换行符(如有)
    size_t len = strlen(dir_path);
    if (len > 0 && dir_path[len - 1] == '\n')
    {
        dir_path[len - 1] = '\0';
    }

    listFile(dir_path); // 调用listFile函数

    return 0;
}

类似文章还有C/C++ 操作文件常用的函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值