我可以运行下面的命令
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 无法识别。我该怎么做才能正确地通过我的程序进行管道传输?
最佳答案
您不应该使用 fgets
和 puts
来处理二进制数据。 fgets
将在看到换行符时停止。更糟糕的是,puts
将输出额外的换行符,并且它也会在遇到\0 时停止。请改用 fread
和 fwrite
。
关于c - 在 C 中使用 popen() 不成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/839232/