以下是使用 C 语言实现遍历目录、移动文件并检查子目录的示例代码

以下是使用 C 语言实现遍历目录、移动文件并检查子目录的示例代码: 

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>

void moveFile(const char *srcPath, const char *destPath) {
    if (rename(srcPath, destPath) == -1) {
        perror("Failed to move file");
    }
}

void traverseDirectory(const char *dirPath, const char *destDir) {
    DIR *dir;
    struct dirent *entry;
    struct stat st;

    dir = opendir(dirPath);
    if (dir == NULL) {
        perror("Unable to open directory");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        char filePath[1024];
        snprintf(filePath, sizeof(filePath), "%s/%s", dirPath, entry->d_name);

        if (stat(filePath, &st) == -1) {
            perror("Failed to get file info");
            continue;
        }

        if (S_ISREG(st.st_mode)) {  // 文件类型为普通文件
            char destPath[1024];
            snprintf(destPath, sizeof(destPath), "%s/%s", destDir, entry->d_name);
            moveFile(filePath, destPath);
        } else if (S_ISDIR(st.st_mode) && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {  // 文件类型为目录
            char subDirPath[1024];
            snprintf(subDirPath, sizeof(subDirPath), "%s/%s", dirPath, entry->d_name);

            // 检查子目录在目标目录下是否存在,不存在则创建该目录
            char subDestDir[1024];
            snprintf(subDestDir, sizeof(subDestDir), "%s/%s", destDir, entry->d_name);
            if (access(subDestDir, F_OK) != 0) {
                if (mkdir(subDestDir, S_IRWXU | S_IRWXG | S_IRWXO) != 0) {
                    perror("Failed to create directory");
                    continue;
                }
            }

            traverseDirectory(subDirPath, subDestDir);
        }
    }

    closedir(dir);
}

int main() {
    const char *sourceDir = "/path/to/source_directory";
    const char *destinationDir = "/path/to/destination_directory";

    // 检查目标目录是否存在,不存在则创建该目录
    if (access(destinationDir, F_OK) != 0) {
        if (mkdir(destinationDir, S_IRWXU | S_IRWXG | S_IRWXO) != 0) {
            perror("Failed to create destination directory");
            return 1;
        }
    }

    traverseDirectory(sourceDir, destinationDir);

    return 0;
}

在上述代码中,我们定义了两个函数:moveFiletraverseDirectorymoveFile 函数用于移动文件,traverseDirectory 函数用于遍历目录并递归地处理文件和子目录。

traverseDirectory 函数中,我们添加了检查子目录在目标目录下是否存在的逻辑。如果子目录不存在,则使用 mkdir 函数创建该目录,并为其设置权限。

你需要将 sourceDirdestinationDir 分别替换为实际的源目录和目标目录的路径。

请确保在编译和运行代码之前,包含所需的头文件和链接相关的库(如 -ldir)。

通过运行以上 C 代码,它将遍历源目录下的所有文件(包括子目录中的文件),并将它们移动到目标目录中。同时会检查子目录在目标目录下是否存在,不存在则创建该目录。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值