Use thread safe readdir_r instread of readdir

readdir is not reentrant so not guaranteed to be thread safe. Use
readdir_r with our own memory so this is not a problem.