2012-12-22 29 views
2

我想用popen()構建一個字符串數組,但數組中的每個索引都是返回的最後一個字符串。我最終只是想將所有文件的目錄列表放到一個數組中。使用popen()構建一個包含fgets()的數組

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

void main() 
{ 
    FILE *fp; 
    fp = popen("find ~/ -maxdepth 1 -type f", "r"); 
    if (fp == NULL) { printf("Failed to run command\n"); exit; } 

    char path[999]; 
    char* rawdata[999]; 
    int i = 0; 

    while (fgets(path, sizeof(path)-1, fp) != NULL) { 
     rawdata[i] = path; // Shouldn't this assign every index 
     i++;    // a different string ? 
    } 
    pclose(fp); 

    /* Below, every index is the same string ? */ 
    printf("\n%s", rawdata[0]); 
    printf("\n%s", rawdata[1]); 
    printf("\n%s", rawdata[2]); 
} 
+0

,因爲你只是在做你大概可以使用http://rosettacode.org/wiki/Walk_a_directory/Recursively#C上授予可能缺失二進制,而不是一個popen方法步行dirtree,大多數系統確實有找,但會更慢 – technosaurus

回答

3
rawdata[i] = path; // Shouldn't this assign every index a different string? 

號要存儲path,這是一個陣列的名稱,因此衰變進指針指向數組的開始。所以實際上,rawdata的所有元素都具有相同的值,並且這是數組path的地址,它永遠不會改變。

實際得到的path複製到rawdata的內容,你需要在rawdata[i]malloc)爲它分配內存,然後使用strcpy。這方面的一個快捷方式存在於所謂的strdup標準庫:

... 

    while (fgets(path, sizeof(path)-1, fp) != NULL) { 
     rawdata[i] = strdup(path); 
     if (rawdata[i] == NULL) 
      goto exit_no_mem; 
     i++; 
    } 
    n = i; 

    ... 

    /* in the end */ 
    for (i = 0; i < n; ++i) 
     free(rawdata[i]); 
    return EXIT_SUCCESS; 
exit_no_mem: 
    fprintf(stderr, "Out of memory\n"); 
    return EXIT_FAILURE; 

最後要注意的是,如果你是把硬工資帽上您正在閱讀的元素數量,確保不違反它。也就是說,一旦i達到999,你不應該讀更多的元素。因此:

while (i < 999 && fgets(path, sizeof(path)-1, fp) != NULL) 
+0

謝謝。我還沒有找到strdup(),並且不會在任何合理的時間內清除「路徑」指針。 – JustTired

+0

如果解決了您的問題,請隨時接受答案。 – Shahbaz

相關問題