Your problem is that the stat(2)
system call is failing because your not providing him with the complete path to the files located in the opened directory, in the case you are using your program to open a directory other than the current one.
This explains why your code worked only when opening the current directory.
One solution would be to append the path to the directory you're opening to the name of the file contained in the d_name
member of the dirent
structure such as :
/path/to/my/directory/name_of_the_file
or
path/to/my/directory/name_of_the_file