Matthew
Matthew

Reputation: 11

reading a file in a subdirectory

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);

}    

Upvotes: 0

Views: 1124

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

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 to

DIR *subDir = opendir(ent->d_name);

tries 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.

Upvotes: 1

Related Questions