简体   繁体   English

C使用dirent.h

[英]C use of dirent.h

Final update - Answer is in the comments of the accepted answer. 最终更新 -答案在接受答案的注释中。

First of all I realize there are a lot of other answers to this question. 首先,我意识到这个问题还有很多其他答案。 I've been through most of them and this code is a combination of going through many other answers. 我经历了其中的大多数,并且此代码是经历许多其他答案的组合。 All I want to do is get to the full path to every file in a directory. 我要做的就是获取目录中每个文件的完整路径。

#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;
}

Update #3: 更新#3:

The call that fails is dir = readdir(d) , which is why I have perror immediately after the while loop. 失败的调用是dir = readdir(d) ,这就是为什么while循环后立即出现错误的原因。

Update #2: 更新#2:

This works just fine on CentOS, and Ubuntu gcc 4.8.5 +. 这在CentOS和Ubuntu gcc 4.8.5 +上可以正常工作。 Does not work on Solaris gcc 4.5.2. 在Solaris gcc 4.5.2上不起作用。

Update: There is an error message: 更新:有错误消息:

Value too large for defined data type 值对于定义的数据类型而言太大

...but I'm not sure what could cause this. ...但是我不确定是什么原因造成的。

This always just prints the current working directory that I'm running the program from. 这总是只打印我正在从中运行程序的当前工作目录。 Even so, it doesn't actually list any of the files in that directory besides "." 即使这样,它实际上也不会列出该目录中除“”之外的任何文件。 and ".." . 和“ ..”。 What gives? 是什么赋予了? Is there some kind of permission issue? 是否存在某种许可问题? Does this solution not work in 2017? 此解决方案在2017年不起作用吗?

the d_name field contains the name of the file in the context of the directory it traverses. d_name字段在其遍历目录的上下文中包含文件的名称。 So, it does not contain any path, just the name. 因此,它不包含任何路径,仅包含名称。

So, in order for you to play with its path, you need to append the d_name to the name of the directory, something like the following: 因此,为了让您使用其路径,您需要将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);

Of course the stuff above is just a skeleton code for clarity. 当然,为了清楚起见,上面的内容只是一个基本代码。 It could be optimized better and you should use strncpy family of functions. 可以对其进行更好的优化,您应该使用strncpy系列函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM