سؤال

So I've written a short C program that explores the files on my computer to look for a certain file. I wrote a simple function that takes a directory, opens it an looks around:

int exploreDIR (char stringDIR[], char search[])
{    
    DIR* dir;
    struct dirent* ent;   

    if ((dir = opendir(stringDIR)) == NULL)
    {
         printf("Error: could not open directory %s\n", stringDIR);
         return 0;             
    }

    while ((ent = readdir(dir)) != NULL)
    {
        if(strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
             continue;

        if (strlen(stringDIR) + 1 + strlen(ent->d_name) > 1024)
        {
            perror("\nError: File path is too long!\n");
            continue;
        }     

        char filePath[1024];
        strcpy(filePath, stringDIR);
        strcat(filePath, "/");
        strcat(filePath, ent->d_name);

        if (strcmp(ent->d_name, search) == 0)
        {
            printf(" Found it! It's at: %s\n", filePath);
            return 1;
        }

        struct stat st; 
        if (lstat(filePath, &st) < 0)
        {
            perror("Error: lstat() failure");
            continue; 
        }

        if (st.st_mode & S_IFDIR)
        {
             DIR* tempdir;
             if ((tempdir = opendir (filePath)))
             {
                 exploreDIR(filePath, search);               
             }

         }

    }
    closedir(dir);
    return 0; 
}

However, I keep getting the output:

Error: could not open directory /Users/Dan/Desktop/Box/Videos
Error: could not open directory /Users/Dan/Desktop/compilerHome

The problem is, I have no idea what it is about these files that could cause opendir() to fail. I don't have them open in any program. They're just simple folders I created on my desktop. Does anyone have any idea what the problem could be?

هل كانت مفيدة؟

المحلول

You are calling opendir() twice for each closedir(). Maybe you are running out of resources.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top