将管道文件内容传递给未知大小的char *(动态分配)

我有一个FILE *来自烟斗(popen),我想把它传递给char *artist 。 将在FILE中的信息大小是未知的,因此它应该使用malloc()

 FILE *tmp1; char *artist; tmp1 = popen("cmus-remote -Q | grep 'tag artist' | sed s/'tag artist'/''/g | sed '1s/^.//'", "r"); 

我怎样才能做到这一点?

这样做的方法是使用临时缓冲区来读取块并将它们附加到艺术家,如下所示:

 char buf[8192]; char *artist = NULL; size_t len = 0, total_len = 0; FILE *fp; fp = popen("cmus-remote -Q | grep 'tag artist' | sed s/'tag artist'/''/g | sed '1s/^.//'", "r"); while (!feof(fp)) { if ( fgets(buf, sizeof(buf), fp) == NULL ) break; len = strlen(buf); artist = realloc(artist, len+1); /* +1 for \0 */ if (artist == NULL) { fprintf(stderr, "Ran out of memory\n"); exit(-1); } strncpy(artist+total_len, buf, len+1); /* concatenate the string at the end of artist */ total_len += len; } 

在具有POSIX getline()的机器上执行此操作的最简单方法是:

 char *buffer = 0; size_t bufsiz = 0; ssize_t nbytes; FILE *tmp1 = popen("cmus-remote -Q | sed -n '/tag artist./ { s/tag artist//g; s/^.//p; }'", "r"); if (tmp1 == 0) …report problem and do not use tmp1… while ((nbytes = getline(tmp1, &buffer, &size)) > 0) { …process line of data… } free(buffer); 

这会将您的行限制为可分配内存的大小; 这很少是一个真正的限制。 请注意,您只需要一个sed命令来处理cmus-remote的输出。