提取

2011-05-19 22 views
1

你能告訴我,怎麼把文件名只(不包括目錄)到我的矢量下面的代碼中?:提取

int getDir (string dir, vector<string> &files) 
{ 
    DIR *dp; 
    struct dirent *dirp; 

    if ((dp = opendir(dir.c_str())) == NULL) { 
     cout << "Error (" << errno << ") with " << dir << endl; 
     return errno; 
    } 

    while ((dirp = readdir(dp)) != NULL) { 
     cout << dirp << endl; 
     files.push_back(string(dirp->d_name)); 
    } 

    closedir(dp); 
    return 0; 
} 
+1

的使用S_ISREG是否套接字,符號鏈接,塊設備,字符設備或FIFO獲得與文件或目錄算的? – 2011-05-19 14:02:30

回答

1

嘗試這樣的:

struct stat eStat; 
stat(dirp->d_name, &eStat); 
if(S_ISDIR(eStat.st_mode)) 
    printf("found directory %s\n", dirp->d_name); 

更好到位S_ISDIR

1

這取決於您的操作系統。在Linux下,由readdir返回的dirent結構是這樣的:

 struct dirent { 
      ino_t   d_ino;  /* inode number */ 
      off_t   d_off;  /* offset to the next dirent */ 
      unsigned short d_reclen; /* length of this record */ 
      unsigned char d_type;  /* type of file; not supported 
              by all file system types */ 
      char   d_name[256]; /* filename */ 
     }; 

,所以你可以檢查d_type現場看到,如果你有一個目錄或文件。

2

您可以使用stat(),並使用S_ISDIR宏檢查st_mode字段。

+0

或'lstat()'如果您需要識別與鏈接到的對象分開的符號鏈接。 – 2011-05-19 14:03:17