通过一个管道文件内容未知大小的char *(动态分配) [英] Pass a pipe FILE content to unknown size char * (dynamic allocated)

查看:244
本文介绍了通过一个管道文件内容未知大小的char *(动态分配)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 FILE * 从管道(的popen),我想将它传递给的char *艺术家
这将是在文件中的信息大小是未知的,所以它应该使用的malloc()

I have a FILE * from a pipe (popen), and I wanna pass it to char *artist. The size of information that will be in the FILE is unknown, so it should use malloc().

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

我怎样才能做到这一点?

How can I do this?

推荐答案

要做到这一点的方法是使用一个临时缓冲区读取数据块,并将其附加到艺术家如下:

The way to do this is to use a temporary buffer to read chunks in and attach them to the artist as following:

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;
}

这篇关于通过一个管道文件内容未知大小的char *(动态分配)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆