Windows – What block allocation algorithm does NTFS use

defragmentfilesystemsntfswindows

On Windows XP 64, I downloaded a 1.2 GB file and it ended up fragmented, as the image shows. Unfortunately, before taking the snapshot from Piriform Defraggler I defragmented the other files, so you can't see the exact state at the point the file was written. However, the disk was all the time about as empty as now (25% used) and hardly fragmented.

screenshot 1

What block allocation algorithm does NTFS use? It looks like random or maybe putting it where the disk head actually stands.

UPDATE:

This is what happened today after writing 67 MiB of a new file. It got split into 731 fragments, average size of only 95 KiB. The file was used to fill some gaps, but not all of them, it doesn't use the huge continuous free space either. Strange, isn't it?

screenshot 2

UPDATE 2:

Unlike PC Guru, I really don't think Opera is the culprit. I think it (as opposed to Google Chrome) doesn't tell Windows the expected size, however, there are many cases when it's not possible and it's the responsibility of the OS to handle it in a sane way. The following picture shows what happened after a couple of days with me doing nearly nothing on this partition – the TEMP directory and all my data (except for those managed by Windows) are both located elsewhere. Windows itself seems not to use SetEndOfFile and fragments its own files in a terrible way (600 fragments for a couple of small file of about 40 MB). NTFS doesn't seem to use the first available sector, as there are again files in the middle and also near the end of the quite empty disk (usage 23%), so the exact algorithm is still unknown.

screenshot 3

Best Answer

IIRC, the NTFS filesystem attempts to allocate the file in contiguous storage. However it can only do that if the filesystem knows the size of the file. If you open a file and start writing to it, it'll write to the "best" place to fit the file (typically towards the outside of the platter). But that "best" place might not be big enough to fit the file.

If the application tells NTFS the actual size of the file (with SetEndOfFile()), NTFS can do a better job of finding contiguous space for the file (the SetEndOfFile API causes NTFS to allocate storage for the entire file).

Related Question