Rather than operate on the raw directory (there used to be a
libext2fs library, not sure what state it is in), you could simply do the following, in your choice of language:
1. create a temporary directory
2. move all the contents of the original directory to the temporary directory, eg using
rename
3. remove the original directory
4. rename the temporary directory back to the original name
This would be more portable (ie, it would work on filesystems other than ext2), and less likely to lead to filesystem corruption if you get it wrong.
I cannot think of many reasons you would want to do this, because spaces left by deleted filename entries are reused anyway.