поиск папок в Паскале
Модераторы: Duncon, Naeel Maqsudov, Игорь Акопян, Хыиуду
- Oleg_Rus
- Сообщения: 335
- Зарегистрирован: 16 окт 2006, 09:56
- Откуда: г.Улан-Удэ, респ.Бурятия, Российская Федерация
- Контактная информация:
Уважаемые обитатели форума, у меня такой вопрос - как сделать поиск папок в паскале?
поиск файлов уже реализовал, а вот с папками какая-то замута получается. Может кто-нить подскажет, как это сделать?
поиск файлов уже реализовал, а вот с папками какая-то замута получается. Может кто-нить подскажет, как это сделать?
e-mail: garmayev@yandex.ru
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>
точно также 
только фильтровать по атрибуту directory

только фильтровать по атрибуту directory
ака хинт: коментируйте код, самим же легче будет разобраться 

- Oleg_Rus
- Сообщения: 335
- Зарегистрирован: 16 окт 2006, 09:56
- Откуда: г.Улан-Удэ, респ.Бурятия, Российская Федерация
- Контактная информация:
можешь привести пример с аргументом? просто я счас на работе, без компилятора. Хочу дома опробовать...
e-mail: garmayev@yandex.ru
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>
вот кусок справки delphi по TSearchRec
type
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
ExcludeAttr: Integer;
FindHandle: THandle;
FindData: TWin32FindData;
end;
...
Attr represents the file attributes of the file. Test Attr against the following attribute constants or values to determine if a file attribe matches the file's properties.
Constant Value Description
faReadOnly $00000001 Read-only files
faHidden $00000002 Hidden files
faSysFile $00000004 System files
faVolumeID $00000008 Volume ID files
faDirectory $00000010 Directory files
faArchive $00000020 Archive files
faAnyFile $0000003F Any file
Note: The faReadOnly constant has the same name as the enumerated value that is defined by the TFieldAttribute type. If both the SysUtils and the Db units are used in your source files, you must disambiguate by specifying the unit to qualify the use of faReadOnly. That is, write SysUtils.faReadOnly.
To test for an attribute, combine the value of the Attr field with the attribute constant with the and operator. If the file has that attribute, the result will be greater than 0. For example, if the found file is a hidden file, the following expression will evaluate to True: (SearchRec.Attr and faHidden) <> 0.
тоесть делаеш поиск файлов и выбираеш из найденных папки
например так
type
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
ExcludeAttr: Integer;
FindHandle: THandle;
FindData: TWin32FindData;
end;
...
Attr represents the file attributes of the file. Test Attr against the following attribute constants or values to determine if a file attribe matches the file's properties.
Constant Value Description
faReadOnly $00000001 Read-only files
faHidden $00000002 Hidden files
faSysFile $00000004 System files
faVolumeID $00000008 Volume ID files
faDirectory $00000010 Directory files
faArchive $00000020 Archive files
faAnyFile $0000003F Any file
Note: The faReadOnly constant has the same name as the enumerated value that is defined by the TFieldAttribute type. If both the SysUtils and the Db units are used in your source files, you must disambiguate by specifying the unit to qualify the use of faReadOnly. That is, write SysUtils.faReadOnly.
To test for an attribute, combine the value of the Attr field with the attribute constant with the and operator. If the file has that attribute, the result will be greater than 0. For example, if the found file is a hidden file, the following expression will evaluate to True: (SearchRec.Attr and faHidden) <> 0.
тоесть делаеш поиск файлов и выбираеш из найденных папки
например так
Код: Выделить всё
if (search.attr and fadirectory)<>0 then
memo1.Lines.Add(search.name);
ака хинт: коментируйте код, самим же легче будет разобраться 

-
- Сообщения: 375
- Зарегистрирован: 31 авг 2007, 03:06
угу. только я бы ещё отбрасывал папки с именами '.' и '..' это служебные папки самой файловой системы. Обычно они для обработки не нужны.
- Oleg_Rus
- Сообщения: 335
- Зарегистрирован: 16 окт 2006, 09:56
- Откуда: г.Улан-Удэ, респ.Бурятия, Российская Федерация
- Контактная информация:
demon416, я использовал такой фрагмент кода
if (search.attr and fadirectory)<>0 then
Writeln(search.name);
в таком разе он ничего не выдает, в то время как используя встроенный хелпик паскаля он выдает максимум все имена файлов.
еще одна ошибка возникает когда пытаешься обратиться к п-ре findFirst u FindNext используя в качестве одного аргумента строку. Пример: FindFirst('*.*', faArchives, ...){запамятовал последний параметр} работает нормально, однако используя код FindFirst(Str, faArchives, ...), где Str: String выдает некую ошибку, номер которой не запомнил.
мож кто поможет? ))
if (search.attr and fadirectory)<>0 then
Writeln(search.name);
в таком разе он ничего не выдает, в то время как используя встроенный хелпик паскаля он выдает максимум все имена файлов.
еще одна ошибка возникает когда пытаешься обратиться к п-ре findFirst u FindNext используя в качестве одного аргумента строку. Пример: FindFirst('*.*', faArchives, ...){запамятовал последний параметр} работает нормально, однако используя код FindFirst(Str, faArchives, ...), где Str: String выдает некую ошибку, номер которой не запомнил.
мож кто поможет? ))
e-mail: garmayev@yandex.ru
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>
-
- Сообщения: 375
- Зарегистрирован: 31 авг 2007, 03:06
Не, ну Вы программист или где?! 1) строку можно использовать!!!! (хотите пример, заодно и все папки Вам найдёт ;-)))) нужен код?" писал(а):еще одна ошибка возникает когда пытаешься обратиться к п-ре ..... где Str: String выдает некую ошибку, номер которой не запомнил
2) когда говорите об ошибке - будьте добры - указывайте какая ошибка, когда возникает, и, желательно, пример кода - скорее всего, Вы использовали строку в функции FindFirst вторым или третьим параметром...
Удачи.
кинь на форму кнопку и мемо
код кнопки
если же хочеться на паскале то давай версию итд
код кнопки
Код: Выделить всё
procedure TForm1.Button1Click(Sender: TObject);
var
search: TSearchRec;
begin
findfirst('c:\*.*',faanyfile,search);
if (search.Attr and fadirectory) <> 0 then
memo1.Lines.Add(search.Name);
while findnext(search)=0 do
if (search.Attr and fadirectory) <> 0 then
memo1.Lines.Add(search.Name);
findclose(search);
end;
ака хинт: коментируйте код, самим же легче будет разобраться 

-
- Сообщения: 375
- Зарегистрирован: 31 авг 2007, 03:06
вот код для TurboPascal:если же хочеться на паскале
Код: Выделить всё
uses Dos;
var
search: SearchRec;
sPath : string;
begin
sPath := 'c:\*.*';
FindFirst(sPath,AnyFile,search);
while ( DosError = 0 ) do begin
if (search.Attr and Directory) <> 0 then
WriteLn(search.Name);
FindNext(search);
end;
end.
- Oleg_Rus
- Сообщения: 335
- Зарегистрирован: 16 окт 2006, 09:56
- Откуда: г.Улан-Удэ, респ.Бурятия, Российская Федерация
- Контактная информация:
именно при таком раскладе на паскале компилер матюгается о несовместимости типов. почитав хелп, я понял, что в процедуре FindFirst первый аргумент является типа PChar и из-за этого возникает ошибка.
-> как отредактировать путь?
мой метод
uses WinDos, Crt;
var ch: char;
path: PChar;
f: text;
Count: integer;
procedure SearchSave(path: PChar);
var
DirInfo: TSearchRec;
begin
Assign(f, FileName); ReWrite(f); Close(f);
Assign(f, FileName); Append(f);
FindFirst(path, faArchive, DirInfo);
while DosError = 0 do
begin
Writeln(DirInfo.Name);
FindNext(DirInfo);
Writeln(f, DirInfo.Name);
inc(count);
end;
Close(f);
end;
label
beg;
begin
ClrScr;
Path:='*.*';
beg:
ch:=readkey;
if ord(ch)=8 then path:='..\'+path else SearchSave(path);
goto beg;
end.
недееспособен, поскольку на строке path:='..\'+path выдает ошибку несовместимости, заменив тип переменной Path c PChar на String выдает ошибку при обращении к процедуре FindFirst.
-> Как это отредактировать??
-> как отредактировать путь?
мой метод
uses WinDos, Crt;
var ch: char;
path: PChar;
f: text;
Count: integer;
procedure SearchSave(path: PChar);
var
DirInfo: TSearchRec;
begin
Assign(f, FileName); ReWrite(f); Close(f);
Assign(f, FileName); Append(f);
FindFirst(path, faArchive, DirInfo);
while DosError = 0 do
begin
Writeln(DirInfo.Name);
FindNext(DirInfo);
Writeln(f, DirInfo.Name);
inc(count);
end;
Close(f);
end;
label
beg;
begin
ClrScr;
Path:='*.*';
beg:
ch:=readkey;
if ord(ch)=8 then path:='..\'+path else SearchSave(path);
goto beg;
end.
недееспособен, поскольку на строке path:='..\'+path выдает ошибку несовместимости, заменив тип переменной Path c PChar на String выдает ошибку при обращении к процедуре FindFirst.
-> Как это отредактировать??
e-mail: garmayev@yandex.ru
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>
---------------------------------------------------------------------------
<a href="http://nick-name.ru/sertificates/711965/"><img src="http://nick-name.ru/img.php?nick=Garmay ... =2&text=t5" alt="Никнейм Garmayev зарегистрирован!" /></a>