Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 10.67 KB | None | 0 0
  1. {$M 32768, 0, 0} {устанавливаем размер стека}
  2. program smartcopy;
  3. uses
  4.    Dos,crt;
  5.    
  6. type
  7.    AttrOnOff = (On, Off, Any);  
  8.    
  9. const
  10.       D : byte = 0;
  11.       C : byte = 3;
  12.       MaxCount = 10; { максимальное число имен (шаблонов) файлов }
  13. var
  14.  
  15.     CountDir,countattr: byte ;
  16.     ExtFiles: string;     { строка для имени (шаблона) выводимых имен файлов }
  17.     CurDir,CurDir1,dirdef,temp,param1,param2: string;      { строка для заۑÐߑPّϠ      }
  18.     i, Count,k : byte;
  19.     count_copied:integer;
  20.     Files : array[1..MaxCount] of string[12]; { массив, где хранятся имена
  21.                                     (шаблоны) удаляемых файлов (не более MaxCount)   }
  22.     ParamReadOnly: AttrOnOff; {/r}
  23.     ParamHidden  : AttrOnOff; {/h}
  24.     ParamSysFile : AttrOnOff; {/s}
  25.     ParamArchive : AttrOnOff; {/a}
  26.     flag1:boolean;
  27.     params:array[1..20] of string;
  28.  
  29.  
  30. procedure copy_traditional(source,dest:pathstr);
  31. var
  32.     f1, f2: file;
  33.     cursor, size, part: longint;
  34.     s: string;
  35.  
  36. begin
  37.     assign (f1,source);
  38.     reset (f1, 1);
  39.     assign (f2,dest);
  40.     rewrite (f2);
  41.     cursor := 0;
  42.     part := 256;
  43.     size := filesize (f1);
  44.     while not eof (f1) do begin
  45.         blockread (f1, s, part);
  46.         blockwrite (f2, s, part);
  47.         inc (cursor, part);
  48.         if (cursor + part) > size then
  49.             part := size - cursor
  50.     end;
  51.     close (f1);
  52.     close (f2);
  53. end;
  54.  
  55. procedure copy_com(path: PathStr; dir_new: DirStr; name: string);
  56. begin
  57.  swapvectors;{обмениваем содержимое векторов прерXX}
  58.  exec('C:\WINDOWS\system32\cmd.exe','/C attrib -h -r -a ' + path);
  59.  exec('C:\WINDOWS\system32\cmd.exe','/C if not exist "'+dir_new+'" mkdir '+dir_new);
  60.  exec('C:\WINDOWS\system32\cmd.exe','/C copy '+ path+ ' '+ dir_new);
  61.  {copy_traditional(path,dir_new+name);}
  62. {запускаем cmd.exe и передаем ему параметры: коа+новая директория}
  63.  inc(count_copied);
  64.  swapvectors;
  65. end;
  66.  
  67. function checkattributes(fileinfo:SearchRec): boolean;
  68. var Mask:byte; Test:boolean;
  69. begin
  70.    Test:=true;
  71.    Mask:= fileinfo.attr;
  72.    Case ParamReadOnly of
  73.       Off: begin
  74.           if (Mask and ReadOnly) = ReadOnly then
  75.                  Test := false end;
  76.       On:  begin
  77.           if (Mask and ReadOnly) <> ReadOnly then
  78.                  Test := false end;
  79.    end; {case}
  80.    if Test then
  81.       Case ParamHidden of
  82.          Off: begin
  83.                  if (Mask and Hidden) = Hidden then
  84.                     Test := false end;
  85.          On:  begin
  86.                  if (Mask and Hidden) <> Hidden then
  87.                     Test := false end;
  88.       end; {Case}
  89.    if Test then
  90.       Case ParamSysFile of
  91.          Off: begin
  92.                  if (Mask and SysFile) = SysFile then
  93.                     Test := false end;
  94.          On:  begin
  95.                  if (Mask and SysFile) <> SysFile then
  96.                     Test := false end;
  97.       end; {Case}
  98.    if Test then
  99.       Case ParamArchive of
  100.          Off: begin
  101.                  if (Mask and Archive) = Archive then
  102.                     Test := false end;
  103.          On:  begin
  104.                  if (Mask and Archive) <> Archive then
  105.                     Test := false end;
  106.       end; {Case}
  107.     checkattributes:=test;
  108. end;
  109.  
  110. procedure scopy(Dir: string; c:byte);
  111. var
  112.     DirInfo : SearchRec;
  113.     FileInfo : SearchRec;
  114.     i: byte;
  115.     folder_part,temp:string;
  116.  
  117. begin
  118.    {$I-}
  119.    ChDir(Dir);                             { Перейти в указанный директорий }
  120.    FindFirst('*.*',AnyFile,DirInfo);       { Построить список всех записей  }
  121.                        {         в указанном директории }
  122.    while DosError = 0 do         { ПОКА НЕ все записи просмотрены ВЫПОЛНЯТЬ }
  123.    begin
  124.       if ((DirInfo.Attr and Directory) = Directory)
  125.          and (DirInfo.name <> '.') and (DirInfo.name <> '..') then
  126.     { ЕСЛИ запись является директорием (за исключением }
  127.     {            директориев с именами '.' и '..' ) ТО }
  128.     begin
  129.         scopy(DirInfo.Name,C+1); { Выполнить рекурсивный спуск        }
  130.                  {             в найденный директорий }
  131.         ChDir('..');                { После завершения его обработки -   }
  132.                          { выполнить рекурсивный подъем в ди- }
  133.                                      { ректорий-хозяин для продолжения    }
  134.                                      { поиска и обработки следующих дир-ев }
  135.     end;
  136.    
  137.     FindNext(DirInfo);       { Взять следующую запись на данном   }
  138.                                { уровне дерева директориев          }
  139.    end;
  140.   { Больше директориев на данном уровне вложенноѰ- }
  141.                                                  { боткой простых файлов }
  142.   for i:=1 to Count do { ДЛЯ всех имен (шаблонов) из массива Files ВЫПОЛНЯТЬ }
  143.   begin
  144.      ExtFiles:=Files[i];
  145.      FindFirst(ExtFiles,AnyFile,FileInfo);  { Построить список всех за- }
  146.                                  { писей на данном уровне дерева дир-ев }
  147.      while DosError = 0 do     { ПОКА НЕ все записи просмотрены ВЫПОЛНЯТЬ }
  148.      begin
  149.         if not (FileInfo.Attr = VolumeId) AND  
  150.            not (FileInfo.Attr = Directory) then
  151.            { Теперь нас интересуют только простые фай- }
  152.            { лы (не директории и не метки тома) с любыми атрибутами }
  153.         begin
  154.             GetDir(D, CurDir);
  155.             if (param1[length(param1)]='/') or (param1[length(param1)]='\') then
  156.             folder_part:=copy(CurDir,length(param1),length(CurDir)-length(param1)+1)
  157.             else
  158.             folder_part:=copy(CurDir,length(param1)+1,length(CurDir)-length(param1)+1);
  159.             if (fileinfo.name<>'THUMBS.DB') and (checkattributes(fileinfo))
  160.                 then copy_com(CurDir+'\'+fileinfo.name,param2+folder_part+'\',fileinfo.name);            
  161.         end;
  162.         FindNext(FileInfo); { Взять следующую запись на данном }
  163.                                { уровне дерева директориев        }
  164.      end;
  165.   end;
  166. end; { scopy}
  167.                                    
  168.  
  169. procedure show_help;
  170. begin
  171.       writeln;
  172.       writeln('Copying one or more files to another place');
  173.       writeln;
  174.       writeln('SCOPY [/R : /-R] [/H : /-H] [/S : /-S] [/A : /-A]');
  175.       writeln('      source destination [template(s)]');
  176.       writeln;
  177.       writeln('  source         Path to the folder you want to copy.');
  178.       writeln('  /R             Copy only files wich have the attribute "ReadOnly".');
  179.       writeln('  /-R            Copy only files which do not have the attribute "ReadOnly".');
  180.       writeln('  /H             Copy only files wich have the attribute "Hidden".');
  181.       writeln('  /-H            Copy only files which do not have the attribute "Hidden".');
  182.       writeln('  /S             Copy only files wich have the attribute "System File".');
  183.       writeln('  /-S            Copy only files which do not have the attribute "System File".');
  184.       writeln('  /A             Copy only files wich have the attribute "Archive File".');
  185.       writeln('  /-A            Copy only files which do not have the attribute "Archive File".');
  186.       writeln('  destination    Path to the folder where you want the files to be copied.');
  187.       writeln('  templates      One or more templates of the files you want to copy.');
  188.       writeln;
  189.       writeln('The key /R can be set from the enviroment variable COPYCMD.');
  190. end;
  191.                                    
  192. begin
  193.   {$I-}       { Отменить системную реакцию на ошибки ввода-вывода }
  194.  
  195.     if (paramstr(1)='/?') then
  196.     begin
  197.       show_help;
  198.       halt(1);
  199.       exit;
  200.     end;
  201.    if ParamCount < 2 then
  202.    begin
  203.       writeln('Command syntax error.');
  204.       halt(1);
  205.       exit;
  206.    end;
  207.    GetDir(D, CurDir1);         { Запомнить директорий, с которого была   }
  208.                               {                        запущена утилита }
  209.    
  210.    ParamReadOnly:= Any; {/r}
  211.    ParamHidden:=Any; {/h}
  212.    ParamSysFile:=Any; {/s}
  213.    ParamArchive:=Any; {/a}
  214.    
  215.    temp:=GetEnv('copycmd');
  216.    if (temp='/r') or (temp='/R') then ParamReadOnly:=On
  217.    else if (temp='/-r') or (temp='/-R') then ParamReadOnly:=Off;
  218.    
  219.    for i:=1 to paramcount do params[i]:=paramstr(i);
  220.    flag1:=true;
  221.    i:=1;
  222.    while flag1 do
  223.    begin
  224.     temp:=params[i];
  225.     if (temp='/r') then ParamReadOnly:=On
  226.     else if (temp='/-r') then ParamReadOnly:=Off
  227.     else if (temp='/h') then ParamHidden:=On
  228.     else if (temp='/-h') then ParamHidden:=Off
  229.     else if (temp='/s') then ParamSysFile:=On
  230.     else if (temp='/-s') then ParamSysFile:=Off
  231.     else if (temp='/a') then ParamArchive:=On
  232.     else if (temp='/-a') then ParamArchive:=Off
  233.     else flag1:=false;
  234.     if flag1 then inc(i);
  235.    end;
  236.    countattr:=i-1;
  237.    
  238.    
  239.    dirdef:=params[countattr+1];
  240.    param1:=dirdef;
  241.    param2:=params[countattr+2];
  242.    ChDir(dirdef);        { Войти в указанный директорий }
  243.    if IOResult <> 0 then    { ЕСЛИ он НЕ найден ТО }
  244.     begin
  245.       writeln('Directory ',dirdef,' not found'); halt(1); { Сообщить об ошибке }
  246.     end
  247.    else                       { ИНАЧЕ }
  248.       begin                  {     Начнем удалять }
  249.          if (ParamCount = 2 + CountAttr) then
  250.             { ЕСЛИ Число параметров командной строки = 2 ТО  }
  251.          begin        {      Обработать режим умолчания: выводить файлы }
  252.                       {      с шаблоном *.* - все файлы }
  253.             Count:=1; Files[1]:='*.*';
  254.             writeln('Using template *.*');
  255.          end
  256.          else            { ИНАЧЕ }
  257.            begin       {   Переписать с командной строки в массив Files }
  258.                         {   имена (шаблоны) удаляемых файлов             }
  259.                Count:=ParamCount-2-countattr+1;
  260.                for i:=1 to Count do
  261.                Files[i]:=ParamStr(i+2+countattr-1);
  262.             end;
  263.             count_copied:=0;
  264.             scopy(param1,0);
  265.       end;
  266.     writeln;  
  267.     writeln(count_copied,' files have been copied');
  268.     writeln;
  269.    ChDir(CurDir1);{ После работы - вернемся в директорий из }
  270.    halt(0);
  271. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement