簡體   English   中英

如何遞歸遍歷目錄並打印C中的所有文件?

[英]How to recursively walk through a directory and print all files in C?

我試圖以遞歸方式遍歷目錄並打印出所有文件。

當我嘗試使用下面的代碼時,例如我用sprint調用函數(“。”,“。”)我得到了一堆點的輸出。

當我減少允許的開放進程數量(ulimit -n 20)時,我得到17個點。 我不明白,因為我認為readdir()和opendir()不會創建新進程。 這是我的代碼:

void sprint(char *filename, char * dirToOpen) {
    DIR *directory = opendir(dirToOpen);
    struct dirent *entry;
    struct stat s;
    char pathname[1024];
    if (directory) { /*if it's a directory*/
       while ((entry = readdir(directory)) != NULL) { /*while there are more entries to read*/
          if(strcmp(entry->d_name, filename) == 0) /*if entry name corresponds to filename, print it*/
             printf("%s\n", filename);
          sprintf(pathname, "./%s", entry->d_name); /*makes pathname*/
          if (lstat(pathname, &s) == 0 && S_ISDIR(s.st_mode)) { /*if the file is a directory*/
             if(strcmp(entry->d_name, "..") != 0 && strcmp(entry->d_name, ".") != 0) /*if the directory isn't . or ..*/
                sprint(filename, entry->d_name);
          }
       }
       closedir(directory);
    }
 }

在某些地方它也沒有到達其余的文件,因為它只打印點,而不是完整的文件名。 我認為這是我最后一個if循環中的某個地方,但我不確定。

這是一個遞歸代碼,它執行以下操作:

void sprint(char *filename, char * dirToOpen, int level = 0)
{
    DIR *dir;
    struct dirent *entry;
    struct stat s;

    if (!(dir = opendir(dirToOpen)))
        return;
    if (!(entry = readdir(dir)))
        return;

    do
    {
        if(lstat(dirToOpen, &s) == 0 && S_ISDIR(s.st_mode)) /*if it's a directory*/
        {
            char path[1024];
            int len = snprintf(path, sizeof(path)-1, "%s/%s", dirToOpen, entry->d_name); /*makes pathname*/
            path[len] = 0;
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) /*if the directory isn't . or ..*/
                continue;
            printf("%*s[%s]\n", level * 2, "", entry->d_name);
            sprint(filename ,path, level + 1);
        }
        else
        {
            if(strcmp(entry->d_name, filename) == 0 || strcmp(filename, ".") == 0) /*if entry name corresponds to filename, print it*/
             printf("%*s- %s\n", 2, "", entry->d_name);
        }
    } while (entry = readdir(dir)); /*while there are more entries to read*/
    closedir(dir);
}

sprint(".", ".");調用它sprint(".", "."); 以遞歸方式遍歷目錄並打印出所有文件。

靈感來自這個答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM