Created
May 15, 2019 12:43
-
-
Save donjajo/4cc8f0cb9f45a9e6733487a5b765bafc to your computer and use it in GitHub Desktop.
List files in directory and sub directories with size and permission
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/stat.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <dirent.h> | |
#include <string.h> | |
void list_files(); | |
void main( int argc, char * argv[] ) { | |
list_files( argv[1], 0 ); | |
} | |
void list_files( char *dir, int sub ) { | |
DIR *d; | |
struct dirent *dir_info; | |
struct stat f_stat; | |
char *real_path = (char*) malloc( PATH_MAX+1 ); | |
realpath( dir, real_path ); | |
strcat( real_path, "/" ); | |
if( ( d = opendir( dir ) ) == NULL ) { | |
perror( "Dir error" ); | |
exit(1); | |
} | |
while( ( dir_info = readdir( d ) ) != NULL ) { | |
char *file_name = (char*) malloc( PATH_MAX+1 ); | |
strcpy( file_name, real_path ); | |
strcat( file_name, dir_info->d_name ); | |
if( stat( file_name, &f_stat ) < 0 ) | |
perror( dir_info->d_name ); | |
if( S_ISDIR( f_stat.st_mode ) > 0 && strcmp( dir_info->d_name, "." ) != 0 && strcmp( dir_info->d_name, ".." ) != 0 ) { | |
list_files( file_name, ( sub + 1 ) ); | |
} | |
else { | |
printf("%s\n", file_name ); | |
printf( "Size: %d\n", f_stat.st_size ); | |
printf( "User: %c%c%c\n", | |
f_stat.st_mode & S_IRUSR ? 'R' : '-', | |
f_stat.st_mode & S_IWUSR ? 'W' : '-', | |
f_stat.st_mode & S_IXUSR ? 'X' : '-' | |
); | |
printf( "Group: %c%c%c\n", | |
f_stat.st_mode & S_IRGRP ? 'R' : '-', | |
f_stat.st_mode & S_IWGRP ? 'W' : '-', | |
f_stat.st_mode & S_IXGRP ? 'X' : '-' | |
); | |
printf( "Others: %c%c%c\n", | |
f_stat.st_mode & S_IROTH ? 'R' : '-', | |
f_stat.st_mode & S_IWOTH ? 'W' : '-', | |
f_stat.st_mode & S_IXOTH ? 'X' : '-' | |
); | |
printf( "\n\n" ); | |
} | |
free( file_name ); | |
} | |
free( real_path ); | |
closedir( d ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment