C 使用 dirent.h

C use of dirent.h

最终更新-答案在已接受答案的评论中。

首先我意识到这个问题还有很多其他的答案。我已经经历了其中的大部分,这段代码是经历了许多其他答案的组合。我只想获取目录中每个文件的完整路径。

#include <limits.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
     DIR *d;
     struct dirent * dir;
     char fullpath[PATH_MAX + 1];
     d = opendir("/home/adirectory");
     if(d != NULL)
     {
          while((dir = readdir(d)) != NULL)
          {
               realpath(dir->d_name, fullpath);
               printf("[%s]\n", fullpath);
               printf("%s\n", dir->d_name);

          }
          // addition of the following line yields
          // Value too large for defined data type
          perror("Something isn't working: ");
          closedir(d);

     }

return 0;
}

更新#3:

调用失败的是dir = readdir(d),这就是我报错的原因 在 while 循环之后。

更新 #2:

这在 CentOS 和 Ubuntu gcc 4.8.5 + 上工作得很好。不工作 Solaris gcc 4.5.2.

更新: 出现错误信息:

Value too large for defined data type

...但我不确定是什么原因造成的。

这总是只打印我 运行 程序所在的当前工作目录。即便如此,它实际上并没有列出该目录中除“。”之外的任何文件。和 ”..” 。是什么赋予了?是否存在某种许可问题?这个解决方案在 2017 年行不通吗?

d_name 字段包含文件在其遍历的目录上下文中的名称。所以,它不包含任何路径,只包含名称。

因此,为了让您玩转它的路径,您需要将 d_name 附加到目录名称,如下所示:

 char *myHomeDir = "/home/adirectory";
 d = opendir(myNomDir);
 . . .
 while((dir = readdir(d)) != NULL) {
    char filepath[PATH_MAX + 1] ;
    strcpy(filepath, myHomeDir);
    strcat(filepath, "/");
    strcat(filepath, dir->d_name);
    realpath(filepath, fullpath);

当然,为了清楚起见,上面的内容只是一个框架代码。它可以优化得更好,你应该使用 strncpy 系列函数。