目录cp

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
typedef void (*PF)(char* name,char* destname);
void dirwalk(char* dir , PF fcn, char* dest)
{
    char name[1024] = {0};
    char destname[1024] = {0};
    struct dirent* dp = NULL;
    DIR* dfd = NULL;
    if(NULL == (dfd = opendir(dir)))
    {
        fprintf(stderr,"dirwalk: cannot open %s",dir);
        return;
    }
    while(dp = readdir(dfd))
    {
        if(!strcmp(dp->d_name,".")|| !strcmp(dp->d_name,".."))
        {
            continue;
        }
        if(strlen(dir) + strlen(dp->d_name) + 2 > sizeof(name))
        {
            fprintf(stderr,"dirwalk:name %s %s too long\n",dir,dp->d_name);
        }
        else
        {
  sprintf(name,"%s/%s",dir,dp->d_name);
  sprintf(destname,"%s/%s",dest,dp->d_name);//???
            fcn(name,destname);
        }

    }
    closedir(dfd);
}
void cp_file(char * src_path,char* dest_path)
{
    int fd = open(src_path, O_RDONLY);
    int n;
    int buf[1024];
    if(fd < 0)
    {
        perror("open file");
        exit(1);
    }
    int fd1 = open(dest_path, O_RDWR | O_TRUNC | O_CREAT, 0644);
    while((n =read(fd, buf, 100)) != 0){
        write(fd1, buf, n);
    }
    close(fd);
}
void fsize(char * name,char * destname)
{
    struct stat stbuf;
    if(-1 == stat(name, &stbuf))
    {
        fprintf(stderr, "fsize: cannot access %s\n",name);
        return;
    }
    else
    {
        if(S_ISDIR(stbuf.st_mode))
        {
            //创建目录
            mkdir(destname,0755);//???
            dirwalk(name,fsize,destname);//???
        }
        else
        {
            cp_file(name,destname);
        //printf("%8ld %s\n",stbuf.st_size, name);
        }
    }
}

int main(int argc, char* argv[])
{
    dirwalk(argv[1],fsize,argv[2]);
    //fsize(argv[1],argv[2]);//???

}

posted @ 2013-08-05 16:37  时来Y运转  阅读(185)  评论(0编辑  收藏  举报