Скачиваний:
13
Добавлен:
01.04.2014
Размер:
2.41 Кб
Скачать
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include<fstream>
#include<iostream>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>


using namespace std; 
void mycopyfile(const char *source_file,const char *destination_file)
{   
    ifstream in(source_file);
    ofstream out(destination_file);
    out<<in.rdbuf(); // copy file 
    in.close();
    out.close(); 
}

int main(void)
{
    DIR *dir1,*dir2;
    struct dirent *entry1,*entry2;
    struct stat *buf;
    int flag,flag_name,k,i,m,cur,NPROC;
    string in_str,out_str;
    pid_t pids[1024],pid_end;
    int file_o;
    char str_dir1[80],str_dir2[80] ;
    
    printf("Dir1 \n");
    scanf("%s",str_dir1);
    printf("Dir2 \n");
    scanf("%s",str_dir2);
    printf("N \n");
    scanf("%d",&NPROC); 
       
    dir1 = opendir(str_dir1);
    dir2 = opendir(str_dir2);

    if ((!dir1)||(!dir2)){
        perror("diropen");
        return 1;
    };
    i = 0;   
    while ((entry1 = readdir(dir1)) != NULL){
      flag = 1;
      while ((entry2 = readdir(dir2)) != NULL){
        for(flag_name = 1,k=0;(k<MAXNAMLEN)&&(entry1->d_name[k] != '\0')&&(entry1->d_name[k] != '\0');k++)
        {  if(entry1->d_name[k] != entry2->d_name[k])flag_name = 0;
        }
        if((flag_name == 1)&& 
	   (entry1->d_type == entry2->d_type)&&
	   (entry1->d_reclen == entry2->d_reclen)
          )flag = 0;
      };
      rewinddir(dir2);
      if(flag){
        if(i == NPROC){
	    pid_end = wait(NULL);//wait end process        
	    for(m = 0;(m < NPROC)&&(pids[m] != pid_end); m++);//find num end process
	    cur = m;
        }
        else cur = i;
	pids[cur] = fork();
        if(pids[cur] < 0) {
            perror("fork");
            return 1;
        } else if(!pids[cur]) {     
	    in_str = str_dir1;
            in_str += "/";
	    in_str +=  entry1->d_name;
	    out_str = str_dir2;
            out_str += "/";
	    out_str += entry1->d_name; 
	    mycopyfile(in_str.c_str(),out_str.c_str()); 
            file_o = open(in_str.c_str(),O_RDONLY);
            fstat(file_o,buf);
            close(file_o);
            printf ("%d %s %d \n", getpid(),entry1->d_name,buf->st_size);//   
            if(i < NPROC) i++;
        }
      }
    };

    closedir(dir1);
    closedir(dir2);
    /*wait end all process */
    for(i = 0; i < NPROC; i++)
       waitpid(pids[i], NULL, 0);
    return 0;
};