Reputation: 2262
I am trying to print all the files' and folders' names inside a directory and its subdirectories. The problem is that files are also considered directories? Sorry for posting my whole code, but I really don't have any idea why this is happening. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
void parcurgere(char path[1000]){
char aux[1000];
strcpy(aux, path);
struct dirent *ent;
DIR *d = opendir(path);
while((ent = readdir(d))){
struct stat my_stat;
stat(path, &my_stat);
if(S_ISDIR(my_stat.st_mode) && strcmp(ent->d_name, ".")!=0 && strcmp(ent->d_name, "..")!=0 && strcmp(ent->d_name, ".DS_Store")!=0){
printf("%s - folder\n", ent->d_name);
char x[1000];
strcpy(x, path);
strcat(x, "/");
strcat(x, ent->d_name);
parcurgere(x);
}
if(S_ISREG(my_stat.st_mode)){
printf("%s - fisier\n", ent->d_name);
}
strcpy(path, aux);
//path[strlen(path) - poz] = '\0';
}
}
int main(){
char path[1000];
strcpy(path, ".");
parcurgere(path);
return 0;
}
Upvotes: 1
Views: 1957
Reputation: 1
You're calling stat()
on the directory you opened with opendir()
:
DIR *d = opendir(path);
while((ent = readdir(d))){
struct stat my_stat;
stat(path, &my_stat);
So yes, the contents of my_stat
indicate that it's a directory - because path
is a directory.
You're also not checking the return code from stat()
. That can fail, and if you do change path
to stat()
the entry returned from readdir()
, you will get incorrect results if stat()
fails.
Upvotes: 4