cunixdirectory-traversal

directory traverse c


I'm trying to traverse a directory and check for duplicate files.

void findDuplicates(){
    char *dot[] = {".", 0};
    FTS *ftsp, *temp_ftsp;
    FTSENT *entry, *temp_entry;
    int fts_options = FTS_LOGICAL;
    ftsp = fts_open(dot, fts_options, NULL);
    while((entry = fts_read(ftsp)) != NULL){
        temp_ftsp = ftsp;
        while((temp_entry = fts_read(temp_ftsp)) != NULL){
            compareEntries(temp_ftsp, ftsp);
        }
    }
}

But it doesn't traverse the directory the way I wanted to. After the 2nd while loop, the

entry = fts_read(ftsp)

returns NULL. Is there an easy fix for this or I should use something else?


Solution

  • You need to re-structure your approach. The inner while is exhausting the list of files, so of course the outer will fail after succeeding, once.

    A better approach is probably to store the files so you can just compare each new incoming file against the stored ones, or use a recursive approach. Both will require memory.