I have a little doubt as to the gnu code, why is it so complex and long? Other systems facing the same problem have a much simpler implementation, for example the ls command in gnu:
http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=blob;f=src/ls.c;h=556313c71ebeb853c3fe9cf3c0312639de8aded0;hb=HEAD And in other system, for example, freebsd, is more simple: https://github.com/freebsd/freebsd/blob/master/bin/ls/ls.c