2011-07-11 26 views
0

我必須創建一個包含在特定目錄內的文件的列表,我已經完成了下面的代碼(更大程序的一部分),但是我希望我的程序忽略可能包含在目錄中的任何可能的文件夾。只獲取包含在c/Ubuntu目錄中的文件

#include <stdio.h> 
#include <sys/types.h> 
#include <dirent.h> 


int main() 
{ 
    DIR *dirptr; 
    struct dirent *entry;  
    dirptr = opendir ("synchedFolder"); 



    if (dirptr != NULL) 
    { 
    while (entry = readdir (dirptr)) 
    { 
     if(strcmp(entry->d_name,"..")!=0 && strcmp(entry->d_name,".")!=0) 
      puts (entry->d_name); 

    } 

    (void) closedir (dirptr); 
    } 
    else 
    perror ("ERROR opening directory"); 



} 
+0

你不能使用shell腳本? – Makis

回答

2

如果你想只列出文件,但沒有目錄,你必須添加以下檢查:

entry->d_type == DT_REG 

entry->d_type != DT_DIR 
1

簡短的回答是的dirent結構包括必要的信息:

if (entry->d_type == DT_REG) 
0

檢查統計(或LSTAT)

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/stat.h> 





/* int main (void){ */ 
int main (int argc, char **argv){ 
    int i,result=0; 
    struct stat buf; 

    /* print_S_I_types(); */ 


    for (i=1; i < argc; i++){ 
     if (lstat(argv[i], &buf) < 0) { 
      fprintf(stderr, "something went wrong with %s, but will continue\n", 
        argv[i]); 
      continue; 
     } else { 
      if S_ISREG(buf.st_mode){ 

       printf("argv[%d] is normal file\n",i); 


      }else { 
       printf("argv[%d] is not normal file\n",i); 
      } 
     } 
    } 

    return 0; 
} 
0

工作代碼上市文件(無目錄):

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

int main() 
{ 
    DIR *dir; 
    struct dirent *ent; 
    if ((dir = opendir ("/home/images")) != NULL) 
    { 
     /* print all the files and directories within directory */ 
     while ((ent = readdir (dir)) != NULL) 
     { 
      if(ent->d_type!= DT_DIR) 
      { 
       printf ("%s\n", ent->d_name); 
      } 
     } 
     closedir (dir); 
    } 
    else 
    { 
     /* could not open directory */ 
     perror (""); 
     return EXIT_FAILURE; 
    } 
} 
相關問題