Use a buffer to hold the selected dir., and write the file outside the if/else.
Properly update count when accessing a folder.