首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ popen没有得到所有的标准输出

C++ popen没有得到所有的标准输出
EN

Stack Overflow用户
提问于 2011-04-26 03:40:09
回答 2查看 3.1K关注 0票数 0

基本上,我想在使用popen运行程序时从stdout中读取所有数据。但是,我运行的程序不会将最后一个输出行返回到我的缓冲区中,我不明白为什么(我的理解是:我会从popen将任何输出发送到stdout {unbuffered?} )。

代码语言:javascript
复制
// $Id: popen.cpp 126 2011-04-25 18:48:02Z wus $

#include <iostream>
#include <stdio.h>

using namespace std;

/**
 * run debians apt-get and check output
 */
int main(int argc, char **argv, char **envp) { 

    FILE *fp;
    char buffer[9];
    // select a package which is not installed and has uninstalled dependencies, 
    // apt-get will ask if it should installed «Y» or nor «n».
    char command[255] = "apt-get install python-wxtools";
    cout << command << endl;

    // Execute command, open /dev/stdout for reading
    fp = popen(command, "r");

    // read output character by character
    while (fread(buffer, 1, 1, fp) != EOF) {
        cout << buffer;
    }

    // close
    pclose(fp);
}

本机输出如下所示:

代码语言:javascript
复制
$ sudo apt-get install python-wxtools
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  python-wxgtk2.8 python-wxversion
Suggested packages:
  wx2.8-doc wx2.8-examples ruby wish tk8.5 tcsh csh octave3.0 mksh pdksh
  python-xml editra
The following NEW packages will be installed:
  python-wxgtk2.8 python-wxtools python-wxversion
0 upgraded, 3 newly installed, 0 to remove and 8 not upgraded.
Need to get 5,942kB of archives.
After this operation, 25.0MB of additional disk space will be used.
Do you want to continue [Y/n]?

注意:在最后一行的末尾没有换行符。

当我使用我自己的程序时,最后一行丢失了(输出)

代码语言:javascript
复制
$ sudo ./test/popen 
g++ -Wall -o test/popen test/popen.cpp
test/popen.cpp: In function ‘int main(int, char**, char**)’:
test/popen.cpp:22: warning: comparison between signed and unsigned integer expressions
apt-get install python-wxtools
Reading package lists...
Building dependency tree...
Reading state information...
The following extra packages will be installed:
  python-wxgtk2.8 python-wxversion
Suggested packages:
  wx2.8-doc wx2.8-examples ruby wish tk8.5 tcsh csh octave3.0 mksh pdksh
  python-xml editra
The following NEW packages will be installed:
  python-wxgtk2.8 python-wxtools python-wxversion
0 upgraded, 3 newly installed, 0 to remove and 8 not upgraded.
Need to get 5,942kB of archives.
After this operation, 25.0MB of additional disk space will be used.

注意:输出末尾的换行符

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-26 03:56:59

问题不是你没有读最后一行,问题是你没有显示它,因为cout被行缓冲了。

代码语言:javascript
复制
cout << buffer << flush;

应该行得通。

票数 1
EN

Stack Overflow用户

发布于 2011-04-26 03:51:17

当fread到达文件末尾时,它不返回EOF。相反,它返回0。但我怀疑问题是apt-get检测到它的输入不是tty,因此根本不打印提示符。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5782413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档