以下是使用 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;
}
在上述代码中,我们定义了两个函数:moveFile
和 traverseDirectory
。moveFile
函数用于移动文件,traverseDirectory
函数用于遍历目录并递归地处理文件和子目录。
在 traverseDirectory
函数中,我们添加了检查子目录在目标目录下是否存在的逻辑。如果子目录不存在,则使用 mkdir
函数创建该目录,并为其设置权限。
你需要将 sourceDir
和 destinationDir
分别替换为实际的源目录和目标目录的路径。
请确保在编译和运行代码之前,包含所需的头文件和链接相关的库(如 -ldir
)。
通过运行以上 C 代码,它将遍历源目录下的所有文件(包括子目录中的文件),并将它们移动到目标目录中。同时会检查子目录在目标目录下是否存在,不存在则创建该目录。