2014-11-14 94 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