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

标签 c screenshot popen piping x11

我可以运行下面的命令

xwd -root | xwdtopnm | pnmtojpeg > 屏幕.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);
}

然后我编译并运行程序 ./popen > screen.jpg 但生成的文件 screen.jpg 无法识别。我该怎么做才能正确地通过我的程序进行管道传输?

最佳答案

您不应该使用 fgetsputs 来处理二进制数据。 fgets 将在看到换行符时停止。更糟糕的是,puts 将输出额外的换行符,并且它也会在遇到\0 时停止。请改用 freadfwrite

关于c - 在 C 中使用 popen() 不成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/839232/

相关文章:

C - crypt() - 代码执行 5 个循环或更多比使用 4 个循环但使用相同的参数/哈希需要更长的时间

CUPS 对 cupsGetDests() 的 undefined reference

c - 何时在 C 的嵌套结构中使用指向另一个结构的指针

java - 捕获 Activity 窗口的屏幕截图

c - 如何从 OpenCL 设备写入/读取单个浮点值(缓冲区)

c++ - 使用c++和cygwin sshd服务的黑色截图

css - 如何使用自定义样式在 Reactjs 中使用 html2canvas 截取 DOM 的屏幕截图

python - 在subprocess.Popen中,bufsize适用于哪个文件?

python - 在 Windows 上从 Python 脚本中终止由批处理文件启动的外部进程

python - 我如何格式化命令参数,它们本身是一组带有 Python 子进程模块的命令?