/*
 *
 *
 *  ÇöÀç µð·ºÅä¸® ÀÌÇÏÀÇ.. È¤Àº..
 *  Ã¹¹øÂ° ÀÎÀÚ·Î ³Ñ¾î¿Â µð·ºÅä¸® ÀÌÇÏ·Î..
 *
 *  È­ÀÏÀÌ¸§À» ÀüºÎ ¸®½ºÆÃ~
 *
 ***********************************************************/


#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

#define error( str ) fprintf( stderr, str )
#define error2( str, var ) fprintf( stderr, str, var )

void list_dir( char* dir );

int main( int argc, char* argv[] ){

	int length;
	char current_dir[255];

	memset( current_dir, 0, sizeof(current_dir) );

	if( argc > 1 ){

		length = strlen( argv[1] );
		if( length < 254 )
			strcpy(current_dir,argv[1]);

		if( current_dir[length-1] != '/' )
			strcat(current_dir,"/");

	}
	else
		strcpy(current_dir,"./");

	list_dir(current_dir);


	return 1;
}


void list_dir( char* dir ){

	char buf[255];

	DIR *dp;
	struct dirent *ep;

	struct stat c_stat;

	printf(" %s ", dir );
	//exit(-1);
	
	// µð·ºÅä¸® ÇÚµéÀ» ¿°..
	dp = opendir(dir);
	if( dp == NULL ){

		fprintf( stderr, "%s :", dir );
		switch( errno ){

			case EACCES:
				error( "Permission denied\n" );
				return;
				
			case EMFILE:
				error( "Too many file descriptors in use by process.\n" );
				return;

			case ENFILE:
				error( "Too many files are currently open in the system.\n" );
				return;

			case ENOENT:
				error( "Directory does not exist, or name is empty string.\n" );
				return;

			case ENOMEM:
				error( " is not a directory.\n" );
				return;

			case ENOTDIR:
				error( "\n" );
				return;

			default:
				error( "Unknown Error.\n" );
				return;

		}

	}

	// dir¿¡¼­ È­ÀÏÀÌ¸§À» ÇÏ³ªÇÏ³ª ÀÐ¾î¿È..
	while( ep = readdir(dp) ){

		memset( buf , 0 , sizeof(buf) );

		strcat( buf , dir );
		strcat( buf , ep->d_name );

		// È­ÀÏÀÌ¸§ÀÌ . ÀÌ³ª .. ÀÌ ¾Æ´Ï¸é..
		if( 0 != strcmp(ep->d_name,".") && 0 != strcmp(ep->d_name,"..") ){

			// µð·ºÅä¸®ÀÎÁö ¾Æ´ÑÁö Ã¼Å©¸¦ À§ÇØ..
			if( stat( buf, &c_stat ) != ENOENT ){

				// µð·ºÅä¸®¸é..
				if(  S_ISDIR( c_stat.st_mode ) != 0){

					// Àç±ÍÈ£Ãâ~
					strcat( buf , "/" );
					list_dir( buf );

				}
				
				// ¾Æ´Ô È­ÀÏÀÌ¸§ Ãâ·Â..
				else
					printf("%s\n", buf );

			}

		}

	}

}



