Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {$M 32768, 0, 0} {устанавливаем размер стека}
- program smartcopy;
- uses
- Dos,crt;
- type
- AttrOnOff = (On, Off, Any);
- const
- D : byte = 0;
- C : byte = 3;
- MaxCount = 10; { максимальное число имен (шаблонов) файлов }
- var
- CountDir,countattr: byte ;
- ExtFiles: string; { строка для имени (шаблона) выводимых имен файлов }
- CurDir,CurDir1,dirdef,temp,param1,param2: string; { строка для заۑÐߑPّϠ }
- i, Count,k : byte;
- count_copied:integer;
- Files : array[1..MaxCount] of string[12]; { массив, где хранятся имена
- (шаблоны) удаляемых файлов (не более MaxCount) }
- ParamReadOnly: AttrOnOff; {/r}
- ParamHidden : AttrOnOff; {/h}
- ParamSysFile : AttrOnOff; {/s}
- ParamArchive : AttrOnOff; {/a}
- flag1:boolean;
- params:array[1..20] of string;
- procedure copy_traditional(source,dest:pathstr);
- var
- f1, f2: file;
- cursor, size, part: longint;
- s: string;
- begin
- assign (f1,source);
- reset (f1, 1);
- assign (f2,dest);
- rewrite (f2);
- cursor := 0;
- part := 256;
- size := filesize (f1);
- while not eof (f1) do begin
- blockread (f1, s, part);
- blockwrite (f2, s, part);
- inc (cursor, part);
- if (cursor + part) > size then
- part := size - cursor
- end;
- close (f1);
- close (f2);
- end;
- procedure copy_com(path: PathStr; dir_new: DirStr; name: string);
- begin
- swapvectors;{обмениваем содержимое векторов прерXX}
- exec('C:\WINDOWS\system32\cmd.exe','/C attrib -h -r -a ' + path);
- exec('C:\WINDOWS\system32\cmd.exe','/C if not exist "'+dir_new+'" mkdir '+dir_new);
- exec('C:\WINDOWS\system32\cmd.exe','/C copy '+ path+ ' '+ dir_new);
- {copy_traditional(path,dir_new+name);}
- {запускаем cmd.exe и передаем ему параметры: коа+новая директория}
- inc(count_copied);
- swapvectors;
- end;
- function checkattributes(fileinfo:SearchRec): boolean;
- var Mask:byte; Test:boolean;
- begin
- Test:=true;
- Mask:= fileinfo.attr;
- Case ParamReadOnly of
- Off: begin
- if (Mask and ReadOnly) = ReadOnly then
- Test := false end;
- On: begin
- if (Mask and ReadOnly) <> ReadOnly then
- Test := false end;
- end; {case}
- if Test then
- Case ParamHidden of
- Off: begin
- if (Mask and Hidden) = Hidden then
- Test := false end;
- On: begin
- if (Mask and Hidden) <> Hidden then
- Test := false end;
- end; {Case}
- if Test then
- Case ParamSysFile of
- Off: begin
- if (Mask and SysFile) = SysFile then
- Test := false end;
- On: begin
- if (Mask and SysFile) <> SysFile then
- Test := false end;
- end; {Case}
- if Test then
- Case ParamArchive of
- Off: begin
- if (Mask and Archive) = Archive then
- Test := false end;
- On: begin
- if (Mask and Archive) <> Archive then
- Test := false end;
- end; {Case}
- checkattributes:=test;
- end;
- procedure scopy(Dir: string; c:byte);
- var
- DirInfo : SearchRec;
- FileInfo : SearchRec;
- i: byte;
- folder_part,temp:string;
- begin
- {$I-}
- ChDir(Dir); { Перейти в указанный директорий }
- FindFirst('*.*',AnyFile,DirInfo); { Построить список всех записей }
- { в указанном директории }
- while DosError = 0 do { ПОКА НЕ все записи просмотрены ВЫПОЛНЯТЬ }
- begin
- if ((DirInfo.Attr and Directory) = Directory)
- and (DirInfo.name <> '.') and (DirInfo.name <> '..') then
- { ЕСЛИ запись является директорием (за исключением }
- { директориев с именами '.' и '..' ) ТО }
- begin
- scopy(DirInfo.Name,C+1); { Выполнить рекурсивный спуск }
- { в найденный директорий }
- ChDir('..'); { После завершения его обработки - }
- { выполнить рекурсивный подъем в ди- }
- { ректорий-хозяин для продолжения }
- { поиска и обработки следующих дир-ев }
- end;
- FindNext(DirInfo); { Взять следующую запись на данном }
- { уровне дерева директориев }
- end;
- { Больше директориев на данном уровне вложенноѰ- }
- { боткой простых файлов }
- for i:=1 to Count do { ДЛЯ всех имен (шаблонов) из массива Files ВЫПОЛНЯТЬ }
- begin
- ExtFiles:=Files[i];
- FindFirst(ExtFiles,AnyFile,FileInfo); { Построить список всех за- }
- { писей на данном уровне дерева дир-ев }
- while DosError = 0 do { ПОКА НЕ все записи просмотрены ВЫПОЛНЯТЬ }
- begin
- if not (FileInfo.Attr = VolumeId) AND
- not (FileInfo.Attr = Directory) then
- { Теперь нас интересуют только простые фай- }
- { лы (не директории и не метки тома) с любыми атрибутами }
- begin
- GetDir(D, CurDir);
- if (param1[length(param1)]='/') or (param1[length(param1)]='\') then
- folder_part:=copy(CurDir,length(param1),length(CurDir)-length(param1)+1)
- else
- folder_part:=copy(CurDir,length(param1)+1,length(CurDir)-length(param1)+1);
- if (fileinfo.name<>'THUMBS.DB') and (checkattributes(fileinfo))
- then copy_com(CurDir+'\'+fileinfo.name,param2+folder_part+'\',fileinfo.name);
- end;
- FindNext(FileInfo); { Взять следующую запись на данном }
- { уровне дерева директориев }
- end;
- end;
- end; { scopy}
- procedure show_help;
- begin
- writeln;
- writeln('Copying one or more files to another place');
- writeln;
- writeln('SCOPY [/R : /-R] [/H : /-H] [/S : /-S] [/A : /-A]');
- writeln(' source destination [template(s)]');
- writeln;
- writeln(' source Path to the folder you want to copy.');
- writeln(' /R Copy only files wich have the attribute "ReadOnly".');
- writeln(' /-R Copy only files which do not have the attribute "ReadOnly".');
- writeln(' /H Copy only files wich have the attribute "Hidden".');
- writeln(' /-H Copy only files which do not have the attribute "Hidden".');
- writeln(' /S Copy only files wich have the attribute "System File".');
- writeln(' /-S Copy only files which do not have the attribute "System File".');
- writeln(' /A Copy only files wich have the attribute "Archive File".');
- writeln(' /-A Copy only files which do not have the attribute "Archive File".');
- writeln(' destination Path to the folder where you want the files to be copied.');
- writeln(' templates One or more templates of the files you want to copy.');
- writeln;
- writeln('The key /R can be set from the enviroment variable COPYCMD.');
- end;
- begin
- {$I-} { Отменить системную реакцию на ошибки ввода-вывода }
- if (paramstr(1)='/?') then
- begin
- show_help;
- halt(1);
- exit;
- end;
- if ParamCount < 2 then
- begin
- writeln('Command syntax error.');
- halt(1);
- exit;
- end;
- GetDir(D, CurDir1); { Запомнить директорий, с которого была }
- { запущена утилита }
- ParamReadOnly:= Any; {/r}
- ParamHidden:=Any; {/h}
- ParamSysFile:=Any; {/s}
- ParamArchive:=Any; {/a}
- temp:=GetEnv('copycmd');
- if (temp='/r') or (temp='/R') then ParamReadOnly:=On
- else if (temp='/-r') or (temp='/-R') then ParamReadOnly:=Off;
- for i:=1 to paramcount do params[i]:=paramstr(i);
- flag1:=true;
- i:=1;
- while flag1 do
- begin
- temp:=params[i];
- if (temp='/r') then ParamReadOnly:=On
- else if (temp='/-r') then ParamReadOnly:=Off
- else if (temp='/h') then ParamHidden:=On
- else if (temp='/-h') then ParamHidden:=Off
- else if (temp='/s') then ParamSysFile:=On
- else if (temp='/-s') then ParamSysFile:=Off
- else if (temp='/a') then ParamArchive:=On
- else if (temp='/-a') then ParamArchive:=Off
- else flag1:=false;
- if flag1 then inc(i);
- end;
- countattr:=i-1;
- dirdef:=params[countattr+1];
- param1:=dirdef;
- param2:=params[countattr+2];
- ChDir(dirdef); { Войти в указанный директорий }
- if IOResult <> 0 then { ЕСЛИ он НЕ найден ТО }
- begin
- writeln('Directory ',dirdef,' not found'); halt(1); { Сообщить об ошибке }
- end
- else { ИНАЧЕ }
- begin { Начнем удалять }
- if (ParamCount = 2 + CountAttr) then
- { ЕСЛИ Число параметров командной строки = 2 ТО }
- begin { Обработать режим умолчания: выводить файлы }
- { с шаблоном *.* - все файлы }
- Count:=1; Files[1]:='*.*';
- writeln('Using template *.*');
- end
- else { ИНАЧЕ }
- begin { Переписать с командной строки в массив Files }
- { имена (шаблоны) удаляемых файлов }
- Count:=ParamCount-2-countattr+1;
- for i:=1 to Count do
- Files[i]:=ParamStr(i+2+countattr-1);
- end;
- count_copied:=0;
- scopy(param1,0);
- end;
- writeln;
- writeln(count_copied,' files have been copied');
- writeln;
- ChDir(CurDir1);{ После работы - вернемся в директорий из }
- halt(0);
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement