I'm given a path to directory with mutiple subdirectories. Every subdirectory has a file with name "st". I'm trying to read every st file from every subdirectory but I always receive a NULL pointer when calling fopen ???
My code:
int main(){
DIR *dir;
struct dirent *ent;
FILE *st;
dir=opendir("/home/me/Desktop/dir/");
while( (ent=readdir(dir)) != NULL ){
if(ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0 ){
DIR *subDir = opendir(ent->d_name);
st = fopen("st", "r");
if(st == NULL){
perror("doesn't exist");
}
}
}
closedir(dir);
}
The problem is that the name in
end->d_name
is just the name of the "file" inside the directory, it's not the complete path, which means your call totries to find the directory in the process current directory.
You need to take the path you passed in to the first
opendir
call and append the new path part.