簡體   English   中英

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上不起作用。

更新:有錯誤消息:

值對於定義的數據類型而言太大

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

這總是只打印我正在從中運行程序的當前工作目錄。 即使這樣,它實際上也不會列出該目錄中除“”之外的任何文件。 和“ ..”。 是什么賦予了? 是否存在某種許可問題? 此解決方案在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系列函數。

暫無
暫無

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

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