2014-11-14 83 views
0

我有一個FILE指針,其中包含來自popen()的輸入。我想把所有的輸入都放到char * str中,但是我不知道如何去做(C編程的新手)。從popen()讀取輸入到char *中C

void save_cmd(int fd) { 
    char buf[100]; 
    char *str; 
    FILE *ls; 
    if (NULL == (ls = popen("ls", "r"))) { 
    perror("popen"); 
    exit(EXIT_FAILURE); 
    } 

    while (fgets(buf, sizeof(buf), ls) != NULL) { 
    //Don't know what to do here.... 
    } 
    pclose(ls); 
} 

我想我無論如何都必須while循環中串聯,但是這怎麼可能當我不知道事先的總大小(我想保存整個結果的char *海峽)。如果任何人有關於如何做到這一點的索引指針,我將非常感激。

+0

一件事你可以這樣操作:用realloc函數,然後你的新的字符串拷貝到 – 2014-11-14 14:57:03

回答

2

所以在你的代碼中,你已經捕獲了一條線到buf

現在你想把* str中的所有變量都變成正確的。

你需要爲它分配內存然後複製。這裏有一個例子:

void save_cmd(int fd) { 
    char buf[100]; 
    char *str = NULL; 
    char *temp = NULL; 
    unsigned int size = 1; // start with size of 1 to make room for null terminator 
    unsigned int strlength; 

    FILE *ls; 
    if (NULL == (ls = popen("ls", "r"))) { 
    perror("popen"); 
    exit(EXIT_FAILURE); 
    } 

    while (fgets(buf, sizeof(buf), ls) != NULL) { 
    strlength = strlen(buf); 
    temp = realloc(str, size + strlength); // allocate room for the buf that gets appended 
    if (temp == NULL) { 
     // allocation error 
    } else { 
     str = temp; 
    } 
    strcpy(str + size - 1, buf);  // append buffer to str 
    size += strlength; 
    } 
    pclose(ls); 
} 
+0

(1)寫'PTR =的realloc(PTR,new_size);'泄漏的分配失敗內存;使用'other = realloc(ptr,new_size); if(other!= 0)ptr = other;'。 (2)計算'strlen(buf)'一次。 (3)使用'strcat()'會導致二次行爲;記錄當前'str'中字符串的長度,然後使用'strcpy(str + len,buf); len + = buflen;'(其中'buflen = strlen(buf);'答案(2))。 – 2014-11-14 15:15:25