2014-01-24 24 views
1

我正在嘗試獲取目錄的內容。理想情況下,我想將它們存儲在一個字符串數組中。除了打開目錄,遍歷其內容以及填充數組之後,是否有辦法在c中執行此操作?C OS X將目錄內容讀入字符串數組

我的工作在一個系統上運行OS X 10.9

回答

2

可以得到分配的目錄與POSIX scandir函數,該函數的路徑和可選的過濾和排序回調,並返回dirent結構的數組列表。 OS X還提供了an equivalent function,它採用塊而不是回調進行排序和過濾。

int scandir(const char *dirname, struct dirent ***namelist, 
      int (*select)(const struct dirent *), 
      int (*compar)(const struct dirent **, const struct dirent **)); 

只是檢索條目的無序列表非常簡單:

int num_entries; 
struct dirent **entries = NULL; 

num_entries = scandir("/", &entries, NULL, NULL); 

for(int i = 0; i < num_entries; i++) 
    puts(entries[i]->d_name); 

//entries is ours to free 
for(int i = 0; i < num_entries; i++) 
    free(entries[i]); 
free(entries); 

POSIX還提供了一個預製的排序功能與SCANDIR的字母順序使用。要使用它,只需通過alphasort作爲最後一個參數。

小心scandir返回錯誤(-1)。上面的代碼的結構是這樣的,明確的檢查是不必要的,但這在更復雜的用途中可能是不可能的。

2

您可能需要使用系統調用的libc和的fopen運行。

這裏是示例代碼,照顧所有數組長度,這裏沒有驗證完成。 的#include 的#include 的#include

int 
main(int argc, char* argv[]) 
{ 
    char cmd[254] = "ls "; 
    char arr[1024]; 
    char line[254]; 
    FILE *fp; 
    if(argc < 2) return -1; 
    if(argv[1]) strcat(cmd, argv[1]); 
     strcat(cmd, " > /tmp/out"); 
    system(cmd); 

    fp = fopen("/tmp/out", "r"); 
    if(!fp){ 
     perror(""); 
     return fprintf(stderr, "could not open /tmp/out!\n"); 
    } 
    while(fgets(line, 254, fp) != NULL) { 
     strcat(arr, line); 
    } 
    printf("%s\n", arr); 
    return 0; 
}