【发布时间】:2011-07-14 21:12:19
【问题描述】:
我已经被这个问题困扰了几天,这真的很令人沮丧。
我正在使用popen() 调用命令行进程并获取其输出并将其存储在C 字符串中。我使用的是fgets(),但似乎换行后会中断,所以我使用的是fread()。唯一的问题是返回的 C 字符串有时会搞砸。
这是我的代码:
const char *cmd = "date";//This the shell command
char buf[BUFSIZ];//Output of the command
FILE *ptr;
int c;
if ((ptr = popen(cmd, "r")) != NULL)
while(fread(buf, sizeof(buf),1, ptr))
while ((c = getchar()) != EOF)
printf("output = %s", buf);
(void) pclose(ptr);
最终的 C 字符串有时包含不应该存在的奇怪字符,或者有时甚至没有可用的字符串。有人可以帮忙吗? ):
编辑:这是我在使用 fgets() 时所做的。不过,Shell 命令可以是任何输出文本的命令。不仅仅是“日期”。
if ((ptr = popen(cmd, "r")) != NULL)<br>while (fgets(buf, BUFSIZ, ptr) != NULL)<br>printf("output = %s", buf);<br>(void) pclose(ptr);
【问题讨论】: