我有一个bash脚本,它打印一个巨大的变量输出行。 我见过的所有示例都使用1024字节左右的固定缓冲区,以便逐行阅读。我怎样才能分配一个可变长度的命令输出?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp;
char path[1024];
/* Open the command for reading. */
fp = popen("bash /home/ouhma/myscript.sh", "r");
if (fp == NULL) {
printf("Failed to run command\n");
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}
/* close */
pclose(fp);
return 0;
}
链接参考:C: Run a System Command and Get Output?
但是,如果我不知道是什么,如果输出线的长度更大的1024个字节? 如何通过使用popen()
命令阅读来处理它?
你可以使用POSIX ['getline()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html)来阅读尽可能长的一行,但只限于内存限制,或者你可以当你还没有收到换行符时,反复调用fgets(),添加一个你根据需要动态分配的缓冲区。这两者都不是很复杂,尽管使用getline()比使用getline()更容易。 –
请注意,如果一行超过1024行,您当前的代码将继续在下一个fgets()调用中读取该行的其余部分。因此,只需打印出文本的当前代码就可以毫无问题地工作。 (然而,如果你想在你的程序中存储一整行并且在一段时间内操作该行 - 你需要看看alk的答案) – nos