Linuxc 폴 더 및 파일 복사 실현

4205 단어 LinuxC
Linuxc 폴 더 및 파일 복사 실현
#include
#include
#include
#include
#include
#include
#include
//       
int is_dir(char *path)
{
    struct stat st;
    stat(path,&st);
    if(S_ISDIR(st.st_mode))
        return 1;
    else
    return 0;
}
//        
int endwith(char *s,char c)
{
//          "/"
    if(s[strlen(s)-1]==c)
        return 1;
    else
        return 0;
}

char* str_contact(char *str1,char *str2)
{
    char* result;
    result=(char*)malloc(strlen(str1)+strlen(str2)+1);
    if(!result)
    {
        printf("      ,        
"); exit(1); } strcat(result,str1); strcat(result,str2); return result; } // void copy1(char* source_path,char* destination_path) { char buffer[1024]; int in,out,size; int fd,fd1; fd=open(source_path,O_RDWR); if(fd==-1) { printf("
"); exit(1); } out=read(fd,buffer,1024); if(out==-1) { printf("
"); exit(1); } close(fd); size=strlen(buffer); fd1=open(destination_path,O_WRONLY|O_CREAT,S_IRWXU|S_IRWXG); if(fd1==-1) { printf("
"); exit(1); } in=write(fd1,buffer,size); if(in==-1) { printf("
"); exit(1); } } // void copy2(char* source_path,char* destination_path) { if(!opendir(destination_path)) { // mkdir if(mkdir(destination_path,0777)) printf("
"); } char *path; path=(char*)malloc(512); // String path="", C // path 512 , path=str_contact(path,source_path); struct dirent* filename; DIR* sn=opendir(path); while(filename=readdir(sn)) { // DIR , memset(path,0,sizeof(path)); path=str_contact(path,source_path); char* file_source_path; file_source_path=(char*)malloc(512); if(!endwith(source_path,'/')) { file_source_path=str_contact(file_source_path,source_path); file_source_path=str_contact(source_path,"/"); } else { file_source_path=str_contact(source_path,"/"); } char* file_destination_path; file_destination_path=(char*)malloc(512); if(!endwith(destination_path,'/')) { file_destination_path=str_contact(file_destination_path,destination_path); file_destination_path=str_contact(destination_path,"/"); } else { file_destination_path=str_contact(file_destination_path,destination_path); } // file_source_path=str_contact(file_source_path,filename->d_name); file_destination_path=str_contact(file_destination_path,filename->d_name); if(is_dir(file_source_path)) { if(!endwith(file_source_path,'.')) { copy2(file_source_path,file_destination_path); } } // else { copy1(file_source_path,file_destination_path); printf(" %s %s !
",file_source_path,file_destination_path); } } } int main(int argc,char* argv[]) { if(argv[1]==NULL||argv[2]==NULL) { printf(" , ,
"); exit(1); } char* source_path=argv[1]; char* destination_path=argv[2]; DIR* source=opendir(source_path); DIR* destination=opendir(destination_path); if(!source||!destination) { printf("
"); } copy2(source_path,destination_path); return 0; }

터미널 입력:
gcc -o fu fu.c
./fu /usr/local/A/AA/a.txt /usr/local/B
실행 하면 / usr / local / B 에 A 의 AA 디 렉 터 리 와 a. txt 가 더 많아 진 것 을 발견 할 수 있 습 니 다.
참고http://blog.csdn.net/yongh701/article/details/50403256

좋은 웹페이지 즐겨찾기