有人知道如何复制目录,包括所有子目录到另一个文件夹到目前为止,我编写的代码副本是在文本文件和目录上副本,但并未复制所有子目录。在进行进一步之前,我以前曾看过这样的问题,但是没有涵盖我需要知道的内容,或者在那里涵盖了其他语言。
对不起,如果我的代码一团糟。
无论如何,这是我的代码:
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFFERSIZE 4096
#define COPYMODE 0644
#define FILE_MODE S_IRWXU
DIR * directory;
struct dirent * entry;
DIR * directoryTwo;
struct dirent * entryTwo;
struct stat info;
// copyFile
void copyFile(const char * src, const char * dst)
{
FILE * file1, *file2;
file1 = fopen(src, "r");
if(file1 == NULL)
{
perror("Cannot open source file");
fclose(file1);
exit(-1);
}
file2 = fopen(dst, "w");
if(file2 == NULL) {
perror("cannot open destination file");
fclose(file2);
exit(-1);
}
char currentchar;
while((currentchar = getc(file1)) != EOF) {
fputc(currentchar, file2);
}
fclose(file1);
fclose(file2);
}
void goThoughFile(const char * srcFilePath, const char * dst)
{
char srcFile[260];
char dstFile[260];
directory = opendir(srcFilePath);
if(directory == NULL) {
printf("Error");
exit(1);
}
while((entry = readdir(directory)) != NULL)
{
if(strstr(entry->d_name, "DS_Store") || strstr(entry->d_name, ".localized") ||
strstr(".", &entry->d_name[0]) || strstr("..", &entry->d_name[0]))
continue;
else if(entry->d_type == DT_REG)
{
sprintf(srcFile, "%s/%s", srcFilePath, entry->d_name);
sprintf(dstFile, "%s/%s", dst, entry->d_name);
copyFile(srcFile, dstFile);
}
if(entry->d_type == DT_DIR)
{
chdir(dst);
mkdir(entry->d_name, S_IRWXU);
sprintf(dstFile, "%s%s/%s", dst, entry->d_name, "/..");
chdir(dstFile);
mkdir(entry->d_name, S_IRWXU);
}
}
}
int main()
{
goThoughFile(someFilePath, anotherFilePath);
return 0;
}
无法保证使用struct dirent
实现的目标。
您正在检查if(entry->d_type == DT_DIR)
类型目录的文件,但是如果您阅读了readdir(3)
的手册,则在结构的评论中清楚地说明了所有文件系统类型并不支持它。
On Linux, the dirent structure is defined as follows:
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* not an offset; see NOTES */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all filesystem types */
char d_name[256]; /* filename */
};
您必须使用getdents()
。有关更多澄清,请参考此帖子。