在C中不成功使用popen()?

4 c x11 screenshot popen piping

我可以运行以下命令

xwd -root | xwdtopnm | pnmtojpeg > screen.jpg

在Linux下的终端,它将生成我当前屏幕的截图.

我尝试使用以下代码执行以下操作:

#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);
}
Run Code Online (Sandbox Code Playgroud)

然后我编译并运行程序,./popen > screen.jpg但生成的文件screen.jpg无法识别.我怎么能这样做才能正确地管理我的程序?

Lau*_*ves 7

您不应该使用fgetsputs处理二进制数据.fgets只要看到换行符就会停止.更糟糕的是,它puts会输出额外的换行符,并且每当它遇到\ 0时它也会停止.使用freadfwrite替代.