Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Delphi: WinAPI и системное программирование > Дефрагментация


Автор: Dark Wanderer 20.3.2005, 12:06
Интересно как узнать фрагментацию файла и каким способом делается дефрагментация. Слышал, что есть стандартное API.

Автор: p0s0l 20.3.2005, 16:56
Да... В 2k/XP есть Defragmentation API, который юзается через DeviceIoControl... Врочем вот:
Цитата(MSDN)
Defragmenting Files

As a file is written to the disk, the file may not be written in contiguous clusters. Noncontiguous clusters slow down the process of reading and writing the file. The farther apart on the disk the noncontiguous clusters are, the worse the problem because of the time it takes to move the hard drive's read/write head. A file with noncontiguous clusters is said to be fragmented. To optimize files for fast access, a volume may be defragmented.

Defragmentation is the process of moving portions of files around on the disk in order to defragment files; that is, the process of moving a file's clusters on the disk to make them contiguous.


In a simple single-tasking operating system, defragmentation is straightforward: the defragmentation software is the sole task, and there are no other processes to read from or write to the disk. However, in a multitasking operating system, some processes may be reading from and writing to the hard drive while another process is trying to defragment that hard drive. The trick is to avoid writes to the file being defragmented without stopping the writing process for very long. Solving this problem is not trivial, but it is possible.

To allow defragmentation without requiring detailed knowledge of the disk structure of the file system, a set of three control codes is provided. These enable applications to locate empty clusters, determine the disk location of file clusters, and move clusters on the disk. They transparently handle the problem of inhibiting and allowing other processes to read from and write to files during moves.

These operations can be performed without inhibiting other processes from running. However, the other processes will have slower response times while a disk drive is being defragmented.

To defragment a file, use the following steps:

1. Use the FSCTL_GET_VOLUME_BITMAP control code to find a place on the volume large enough to accept the entire file. If necessary, move other files to make a place that's large enough. Ideally, there will be enough unallocated clusters after the first extent of the file that you can simply move subsequent extents into the space after the first extent.
2. Use the FSCTL_GET_RETRIEVAL_POINTERS control code to get a map of the current layout of the file on the disk.
3. Walk the RETRIEVAL_POINTERS_BUFFER structure returned by FSCTL_GET_RETRIEVAL_POINTERS. Use the FSCTL_MOVE_FILE control code to move each cluster as you walk the structure. You may need to renew either the bitmap or the retrieval structure, or both, from time to time as other processes write to the disk.

Two of the operations used in the defragmentation process require handles to volumes. Only administrators can open volumes to handles, so only administrators can defragment volumes. Your program should check the privileges of the user attempting to run defragmentation software, and it should not execute if the user does not have the appropriate credentials.

When using CreateFile to open a directory during defragmentation of a FAT or FAT32 volume, do not specify the MAXIMUM_ALLOWED access mask value. Access to the directory will be denied if this is done. Specify the GENERIC_READ access mask value instead.

Do not attempt to move allocated clusters in an NTFS file system that extend beyond the cluster rounded file size. If attempted, this will result in an error condition.

Reparse points, bitmaps, and attribute lists in NTFS volumes can be defragmented under Windows XP. Each of these can be opened for reading and synchronization, and are named using the file:name:type syntax—for example, $i30:$INDEX_ALLOCATION, mrp::$DATA, mrp::$REPARSE_POINT, and mrp::$ATTRIBUTE_LIST.

Under Windows XP, NTFS defragments uncompressed files at the cluster boundary. Under Windows 2000, this was done at the page boundary.

Under Windows 2000, an attempt to defragment the space between the file size and the allocation size will fail. However, you can do this under Windows XP.

When defragmenting NTFS volumes, defragmenting a virtual cluster beyond the file's allocation size is allowed.

Автор: Dark Wanderer 20.3.2005, 20:19
p0s0l Спасибо, может у тебя исходник какой есть: хоть на С++, хоть на Delphi?

Автор: p0s0l 20.3.2005, 22:13
Тут описан принцип и есть исходник на сях:
http://www.sysinternals.com/ntw2k/info/defrag.shtml
Добавлено @ 22:16
Еще один линк (исходники не смотрел... но возможно с комментариями на русском):
http://www.mtu-net.ru/pinetar/dm/comp_ntfs_frag.htm
Только тут сказано, что не очень рабочий дефрагментатор smile
Также там сказано про одну корявую особенность Defragmentation API...

Автор: Dark Wanderer 24.3.2005, 14:39
После прочтения стать в Дефрагментаторах разочаровался...
Но спасибо большое за линки!

Автор: Softaz 3.3.2007, 10:23
Цитата(p0s0l @  20.3.2005,  22:13 Найти цитируемый пост)
Тут описан принцип и есть исходник на сях:http://www.sysinternals.com/ntw2k/info/defrag.shtml  Добавлено @ 22:16 Еще один линк (исходники не смотрел... но возможно с комментариями на русском): http://www.mtu-net.ru/pinetar/dm/comp_ntfs_frag.htmТолько тут сказано, что не очень рабочий дефрагментатор Также там сказано про одну корявую особенность Defragmentation API...


Возникла подобная проблема. Надо узнать, как делать дефрагментацию и проверку диска.
Линки умерли.
Есть ли у Вас информация или исходник.

Автор: Snowy 3.3.2007, 12:55
Есть в разделе по плюсам (естественно на плюсах):
http://forum.vingrad.ru/topic-124393/index.html
http://forum.vingrad.ru/topic-139520/index.html
http://forum.vingrad.ru/topic-125926/index.html

Добавлено @ 13:00 
А линки умерли потому что M$ в прошлом году зохавало sysinternals.
Теперь сайт тут: http://www.microsoft.com/technet/sysinternals/

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)