不成功的使用的popen()在C? [英] unsuccesful use of popen() in C?

查看:171
本文介绍了不成功的使用的popen()在C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以运行下面的命令

XWD -root | xwdtopnm | pnmtojpeg> screen.jpg

在linux下的一个终端,它会产生我当前屏幕的屏幕截图。

in a terminal under linux and it will produce a screenshot of my current screen.

我尝试做与code以下内容:

I try to do the following with the code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   FILE *fpipe;
   char *command="xwd -root | xwdtopnm | pnmtojpeg";
   char line[256];

   if ( !(fpipe = (FILE*)popen(command,"r")) )
   {  // If fpipe is NULL
      perror("Problems with pipe");
      exit(1);
   }

   while ( fgets( line, sizeof line, fpipe))
   {
      //printf("%s", line);
      puts(line);
   }
   pclose(fpipe);
}

然后我编译并运行程序 ./的popen&GT; screen.jpg 但是产生的文件screen.jpg是unrecongizable。我怎样才能做到这一点,这样我就可以通过管我的程序是否正确?

then I compile and run the program ./popen > screen.jpg but the resulting file screen.jpg is unrecongizable. How can I do this so that I can pipe through my program correctly?

推荐答案

您不应使用与fgets 看跌处理二进制数据。每当它看到一个新行与fgets 将停止。更糟的是,看跌将输出额外的新行,它也将停止每当运行到一个\\ 0。使用 FREAD FWRITE 代替。

You shouldn't use fgets and puts for dealing with binary data. fgets will stop whenever it sees a newline. Worse, puts will output extra newlines and it will also stop whenever it runs into a \0. Use fread and fwrite instead.

这篇关于不成功的使用的popen()在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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