简体   繁体   中英

writing ls from scratch recursively

I am working on a simple project to implement "ls -R" from scratch. Whenever I run what I have, my program just keeps searching the root directory over and over again. What am I doing wrong?

void lsR(char dirName[]) {
/*
The recursive function call.  
*/

DIR *dir;
struct dirent *directory;
struct stat fileStat;
char type;
char **nameList[MAX_RECURSIVE_FILES];
struct passwd *user;
int count = 0;
int i = 0;


printf("\n");
printf("./%s :\n", dirName);
printf("\n");


if ((dir = opendir(dirName)) == NULL) {
    perror("opendir error:");
    return;
}

while ((directory = readdir(dir)) != NULL) {


    if (stat(directory->d_name, &fileStat) < 0) {
        perror("fstat error:");
        return;
    }
    if (fileStat.st_uid == 1) {
        continue;
    }

    user = getpwuid(fileStat.st_uid);
    printf("%s ", directory->d_name);

    fileType(&fileStat, &type);
    if ((type == 'd') && (count < MAX_RECURSIVE_FILES)) {

        nameList[count] = malloc(sizeof(char)*MAX_STRING_LENGTH);
        strncpy(nameList[count++], directory->d_name, MAX_STRING_LENGTH);
    }

}
closedir(dir);
printf("\n");
for (i=0; i<count; i++) {
    printf("Calling lsR on: %s\n", nameList[i]);
    lsR(nameList[i]);
}

}

When it executes, I get the following output:

"./. :

., .., ... all other files in my current working directory ....

./. :

., .., ... all other files in my current working directory...

"

You need to include the path relative to your program's current directory. Each nameList element will need to be dirName + "/" + directory->d_name .

If you started out calling lsR on the local directory, ./foo and foo has directory named bar under it, then to open bar you need to open ./foo/bar since your program is running from the directory represented by . .

Among the list of files in the current directory you've noticed . and .. The first one is a hardlink to the current directory and the second one to the parent directory. So when you recurse through your dir entries you will want to skip those two. Otherwise the first directory you will recurse into will be . , in other words the directory you've just gone through.

This is the reason of your program current behavior, but once you fix that you will run into the issue lurker mentioned in his answer.

Additional notes :

  • Are you sure about the char **nameList[MAX_RECURSIVE_FILES]; variable? Seems to me you want an array of char * not an array of char ** .
  • Are you aware you can use the S_ISDIR macro on the st_mode field of your stat struct, in order to check that the current file is not a directory instead of your custom function?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM