0

I build my own virtual file system in C.

Now I want to implement some sort of defragmantation method, where it looks for gaps and closes them.

So if file 1 is size 10 and on position X and file 2 is size 20 and on position Z, I want it to get moved to position Y.

My idea now is to take the size File 2, substract it from the size of File 1 and use the outcome to shift File 2 to the left as high as the outcome.

I have a pseudo code, because I can't come up with a working solution:

for (int i = 0; i < files; i++) 
     //look for inconsistencies/gaps. 

if (found gaps)
    file 2 - file 1 = x;
    shiftfiletotheleft x bytes;

Thanks for ideas and answers in advance.

XCoderX
  • 71
  • 1
  • 9

1 Answers1

0

Naive fragmentation is fairly simple, assuming disk[n] refers to the n-th block and files is the set of all files (or more precisely, the blocks they occupy), including a pseudo file for all remaining blocks:

i = 0
for file in files:
  for blocknum in file:
    // Swap content
    buf = disk[i]
    disk[i] = disk[blocknum]
    disk[blocknum] = buf

    // Swap metadata
    swap_block(file, blocknum, i)
    file += i
    changed_file = find_file_by_block(blocknum)
    swap_block(changed_file, i, blocknum)

    i += 1

Note that a variety of optimizations is possible, and necessary for good user experience. For example, since you need to look up files by block number anyways, you can prevent an already-defragmented filesystem from being reordered by always picking the file that the currently-inspected (i-th) block belong to. Additionally, you can of course simplify swapping by not actually copying over the contents if the file you're swapping with is empty, and skipping the swapping action entirely if blocknum and i are identical.

How that pseudo code translates to C code entirely depends on your implementation though.

phihag
  • 278,196
  • 72
  • 453
  • 469