为什么我使用dirent得到错误的目录内现有文件数?

时间:2014-11-26 12:09:39

标签: c count dirent.h

我写了一个小函数,它接收文件夹的路径,并应该返回其中的文件数。

出于某种原因,我的答案不正确:打印时我看到它打印...

有人可以告诉我为什么吗?减少2会解决吗?

以下是代码:

    {
    struct dirent *entry;
    DIR *dirp;
    int fileCount = 0;
    char currPath[MAX_STR];
    dirp = opendir(clientLocalPath);
    printf(" ***** printing files!!!!! ********\n");
    while((entry = readdir(dirp)) != NULL)
    {
            strcpy(currPath, entry->d_name);
            printf("%s\n",currPath);
            fileCount++;

    }
    closedir(dirp);
    return fileCount;
}

3 个答案:

答案 0 :(得分:2)

.是当前目录

..是父目录

在扫描文件时,您会在每个文件夹中找到这两个名称。获取文件名时,您可以通过检查代码中的名称来忽略这两个值。

例如 "..\tmp.txt"指定名为tmp.txt的文件,该文件位于当前目录的父级

答案 1 :(得分:2)

这种行为完全正常。 ...分别表示当前目录和父目录。如果你想忽略它们并考虑fileCount变量的其余文件,你可以这样做:

while((entry = readdir(dirp)) != NULL)
{
    if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                    printf("\0");
    else
    {
        strcpy(currPath, entry->d_name);
        printf("%s\n",currPath);
        fileCount++;
    }
}

答案 2 :(得分:1)

这是正常的,因为...都是目录的一部分:.引用当前的...到父目录。

来自What is a dot only named folder?

  

每个目录都包含...条目。

     

..表示目录本身。它被称为当前目录。

     

strcmp表示目录的父目录,即目录   包含它。

来自Why do directory listings contain the current (.) and parent (..) directory?

  

最好的方法是{{1}}而忽略它们,如果你不愿意的话   列出他们。