用C递归目录复制(Recursive directory copying in C)

2019-08-17 06:45发布

我很新的C语言编程,并在任何地方有关于如何做的在C(不是C ++,C#,Objective-C中,爪哇,外壳,Python或其他任何一个目录的内容递归复制几乎有用的信息 - 这必须用C来实现)。 是的,这是家庭作业,这是因为明天晚上,我一直在为被困近两个星期试图完成这件事。

我试图寻找一个给定的目录(如目录“目录”有一个备份目录“/dir.bak”)的任何备份版本。 如果没有,创建一个“/dir.bak”目录下,或者如果有,创建一个名为“/dir.bak.MM-DD-YY-HH-MM-SS”,而不是一个备份目录。 然后从源目录复制到所有的目标目录。

当我尝试运行此代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

#define BUFSIZE 256

int main (int argc, char* argv[])
{
    DIR *dir;
    struct dirent *dentry;
    struct stat statbuff;
    char buffer[BUFSIZE];//holds time and date suffix
    ssize_t count;
    int fdin, fdout;    
    mode_t  perms =  740;//perms for file I/O ops
    char *cwdNamePntr;
    long maxpath;
    if ( argc != 3 ) //if incorrect number of args passed in...
    {
        printf( "Usage: %s Directory-Path-Name Destination-Folder\n ", argv[0] );
        exit(1);
    }
    char  buffer2[BUFSIZE];//buffer for file I/O ops
    char* datetime;
    int retval;
    time_t  clocktime;
    struct tm  *timeinfo;
    time (&clocktime);
    timeinfo = localtime( &clocktime );
    strftime(buffer, BUFSIZE, "%b-%d-%Y-%H-%M-%S", timeinfo);//store time and date suffix in case we need it
    chdir(argv[1]);
    char *path = argv[2];//source path for I/O ops
    char *newpath = malloc(strlen(path) + 26);//destination paths for I/O ops
    strcpy(newpath,path);
    strcat(newpath,".bak");//test name for backup directory
    if(chdir(newpath)==0)
    {//if our test name is already a directory
        chdir("..");
        strcat(newpath,".");
        strcat(newpath,buffer);//add time and date suffix onto the name of new backup directory
    }
    if ( (mkdir(newpath, perms)) == 0 )//if we successfully made a new backup directory
    {
        chdir(path);
        dir = opendir(".");//move into source directory
        if ( dir ==  0 )
        {//if open directory fails
                fprintf (stderr, "Error in opening directory:  %s\n", path );
            perror( "Could not open directory");
                exit(2);
        }
        dentry = readdir (dir);//load directory

        while (dentry != 0)//while we are reading a directory
        {
            char *filename = dentry->d_name;//get name of file to be copied
            if( (strcmp(filename,".")!=0) && (strcmp(filename,"..")!=0) )
            {
                if  ( (fdin = open ( filename,  O_RDONLY))  == -1)
                {//if cannot open input file
                        perror ( "Error in opening the input file:");
                        exit (2);
                }
                chdir("..");//go back to parent directory
                chdir(newpath);//move to destination directory
                opendir(".");
                if  ( (fdout = open (filename, (O_WRONLY | O_CREAT), perms)) == -1 )
                {//if cannot create output file...
                        perror ( "Error in creating the output file:");
                        exit (3);
                }
                while ( (count=read(fdin, buffer2, BUFSIZE)) > 0 )
                {
                        if ( write (fdout, buffer2, count) != count )
                    {//if cannot write   
                                perror ("Error in writing" );
                                exit(3);
                        }
                } 

                    if ( count == -1 )
                    {//if cannot read
                        perror ( "Error while reading the input file: ");
                        exit(4);
                }

                close(fdin);
                close(fdout);
            }
            chdir("..");//back to parent directory again
            dir = opendir(".");
            if ( dir ==  0 )//if open directory fails
            {
                    fprintf (stderr, "Error in opening directory:  %s\n", path );
                perror( "Could not open directory");
                    exit(666);
            }
            dentry = readdir (dir);//reload directory
        }
    }
    else
    {
        perror("Error in directory creation");
        exit(2);
    }
    return 0;  
}

我得到这个错误:

[my-desktop]@ubuntu:~/Desktop$ ./helpmehelpyou.out ~/Desktop new
Error in creating the output file:: Permission denied

这段代码的一堆是从我们的教官说,我们可以用样本文件拍摄。 我不明白这是为什么不工作的权利? 成品函数必须是递归的,并与这之中选项4. C是我很难把握或理解四自选程序的一部分,就像我说的,有这个东西对C的信息非常少,但一它为过多的C#,C ++,Objective C的,和所有其他的语言。 就像我也说了,我们可以不使用shell命令或任何其他为这项任务。

有人可以帮帮我吗? 谢谢!

Answer 1:

这不会解决你的问题,但我在你的代码发现了一个可能的错误。 我看不到递归发生。

你看,这个代码可以正常工作,如果你只有一个子文件夹。 但是,你会怎么做,如果有在该子文件夹的子文件夹?

你需要一个递归目录搜索功能。 这可能是这样的:

void SearchDirectory(const char *name) {
    DIR *dir = opendir(name);                //Assuming absolute pathname here.
    if(dir) {
        char Path[256], *EndPtr = Path;
        struct dirent *e;
        strcpy(Path, name);                  //Copies the current path to the 'Path' variable.
        EndPtr += strlen(name);              //Moves the EndPtr to the ending position.
        while((e = readdir(dir)) != NULL) {  //Iterates through the entire directory.
            struct stat info;                //Helps us know about stuff
            strcpy(EndPtr, e->d_name);       //Copies the current filename to the end of the path, overwriting it with each loop.
            if(!stat(Path, &info)) {         //stat returns zero on success.
                if(S_ISDIR(info.st_mode)) {  //Are we dealing with a directory?
                    //Make corresponding directory in the target folder here.
                    SearchDirectory(Path);   //Calls this function AGAIN, this time with the sub-name.
                } else if(S_ISREG(info.st_mode) { //Or did we find a regular file?
                    //Run Copy routine
                }
            }
        }
    }
}

此代码将调用该函数SearchDirectory为多次因为有在当前文件夹中的子目录。 如果结构太深,你可能会耗尽内存,程序可能会崩溃,所以请当心。

一旦不能在文件夹中找到任何更多的目录(它已经达到了“leaf'文件夹),它会遍历剩余的文件,然后结束这个函数,从栈中弹出最后一个函数调用,使以前调用SearchDirectory继续搜索。

毕竟是说,做,你就会有一个完整的递归复制。

PS:很抱歉的扰流板,我看了你的评论我做打字之后。



文章来源: Recursive directory copying in C