2024年1月15日发(作者:)
在Linux下,你可以使用C语言中的系统调用和标准库函数来实现拷贝文件夹及其内容的功能。一个常见的方法是使用fork创建子进程,然后在子进程中调用exec来执行cp命令。以下是一个简单的示例代码:
#include
#include
#include
#include
#include
#include
void copyFolder(const char *source, const char *destination) {
pid_t pid = fork();
if (pid == -1) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) { // Child process
execlp("cp", "cp", "-r", source, destination, NULL);
perror("Exec failed");
exit(EXIT_FAILURE);
} else { // Parent process
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
printf("Folder copied successfully.n");
} else {
printf("Folder copy failed.n");
}
}
}
int main() {
const char *sourceFolder = "/path/to/source/folder";
const char *destinationFolder = "/path/to/destination/folder";
copyFolder(sourceFolder, destinationFolder);
return 0;
}
请将/path/to/source/folder替换为源文件夹的实际路径,将/path/to/destination/folder替换
为目标文件夹的实际路径。这个例子使用了fork创建子进程,并在子进程中调用exec来执行cp -r命令,实现了递归拷贝文件夹及其内容。
注意:上述代码中使用的execlp函数会调用系统命令,如果你的系统不支持cp命令或者你需要在不同的环境中运行,可能需要使用其他方式实现文件夹拷贝,比如使用opendir、readdir、mkdir和copyFile等函数手动递归地拷贝文件夹内容。


发布评论